Back to C++
2026-02-029 min read

structure (C++)

Learn structure (C++) step by step with clear examples and exercises.

Why This Matters

In this extensive guide, we delve deep into the intricacies of C++ structures, a powerful feature that sets you apart in programming competitions, job interviews, and real-world projects. Understanding structures will enable you to manage complex data efficiently and write more organized, maintainable code.

Prerequisites

Before diving into structures, it's crucial to have a strong foundation in the following C++ concepts:

  1. Basic syntax and concepts
  2. Data types (int, char, float, etc.)
  3. Variables and their usage
  4. Arrays and pointers
  5. Functions in C++
  6. Standard library functions such as std::cin, std::cout, std::string, and std::vector
  7. Understanding of memory management in C++ (e.g., stack, heap)
  8. Knowledge of classes and objects

Core Concept

A structure in C++ is a user-defined data type that allows you to group related variables under a single name, facilitating the management of complex data. Structures are particularly useful when dealing with records containing multiple fields like name, age, address, etc.

To create a structure, we use the struct keyword followed by the structure name and enclosed within curly braces {}. Each field in the structure is defined with its data type and variable name, separated by commas. Here's an example of a simple structure:

struct Student {
char name[50];
int age;
float gpa;
};

In this example, we have created a structure named Student, which includes three fields: name, age, and gpa.

To access the fields of a structure, we use the dot operator (.). For instance, to print the name of a student, you would write:

Student s; // Declare a Student variable
strcpy(s.name, "John Doe"); // Assign values to the structure fields
cout << s.name; // Print the name

Structures and Memory

When you create a structure, memory is allocated for each field in the structure. The size of the structure is equal to the sum of the sizes of its individual fields. For example, the Student structure we defined earlier would occupy 54 bytes (50 bytes for name + 4 bytes for age + 4 bytes for gpa).

Structures with Custom Member Initialization

C++11 introduced support for custom member initialization in structures. This allows you to initialize structure members during declaration, making it easier to ensure that all members are properly initialized:

struct Student {
char name[50] = {"John Doe"}; // Initialize name with default value
int age = 18; // Initialize age with default value
float gpa = 3.5f; // Initialize gpa with default value
};

Structures and Classes

Note that that structures in C++ are similar to classes, but with some key differences:

  • Structures have public access specifier by default, while classes can be defined with public, private, or protected access specifiers.
  • Structures do not support inheritance, constructors, destructors, or operator overloading, which are features available in classes.

Worked Example

Let's create a program that manages a list of students using structures:

#include <iostream>
#include <string>

struct Student {
std::string name;
int age;
float gpa;
};

int main() {
const int NUM_STUDENTS = 3;
Student students[NUM_STUDENTS];

// Input student data
for (int i = 0; i < NUM_STUDENTS; ++i) {
std::cout << "Enter name: ";
std::getline(std::cin, students[i].name);
std::cout << "Enter age: ";
std::cin >> students[i].age;
std::cout << "Enter GPA: ";
std::cin >> students[i].gpa;
}

// Output student data
for (int i = 0; i < NUM_STUDENTS; ++i) {
std::cout << "\nStudent " << i+1 << ":\n";
std::cout << "Name: " << students[i].name << "\n";
std::cout << "Age: " << students[i].age << "\n";
std::cout << "GPA: " << students[i].gpa << "\n";
}

// Sort students by GPA in descending order using std::sort() function
std::sort(students, students + NUM_STUDENTS, [](const Student &a, const Student &b) { return a.gpa > b.gpa; });

// Output sorted student data
for (int i = 0; i < NUM_STUDENTS; ++i) {
std::cout << "\nStudent " << i+1 << ":\n";
std::cout << "Name: " << students[i].name << "\n";
std::cout << "Age: " << students[i].age << "\n";
std::cout << "GPA: " << students[i].gpa << "\n";
}

// Calculate and output the average GPA of all students
float total_gpa = 0.0f;
for (int i = 0; i < NUM_STUDENTS; ++i) {
total_gpa += students[i].gpa;
}
float avg_gpa = total_gpa / NUM_STUDENTS;
std::cout << "\nAverage GPA: " << avg_gpa << "\n";

return 0;
}

In this example, we have created a program that takes input for three students and stores their data in a structure array. We then iterate through the array to output the stored information using standard library functions. Additionally, we sort the students by GPA in descending order using the std::sort() function and calculate the average GPA of all students.

Common Mistakes

  1. Forgetting to include the header files: Make sure you always include the necessary header files (`, `, etc.) at the beginning of your program.
  2. Not initializing structure variables: Always initialize your structure variables before using them, as structures by default are uninitialized.
  3. Incorrect memory allocation for structures: Be aware that each field in a structure occupies memory, and ensure you allocate enough space for all fields when declaring structures.
  4. Not using the dot operator to access structure fields: Remember to use the dot operator (.) to access the fields of a structure.
  5. Misunderstanding structure size: Keep in mind that the size of a structure is equal to the sum of the sizes of its individual fields.
  6. Using old-style character arrays: Old-style character arrays, such as char name[50], are not null-terminated and can lead to issues when working with strings. Use standard library string types like std::string instead.
  7. Not taking advantage of custom member initialization (C++11 and later): Custom member initialization allows you to set default values for structure members, making it easier to ensure that all members are properly initialized. It also makes your code more concise and easier to read.
  8. Confusing structures with classes: Understand the differences between structures and classes in C++, as they have different features and access specifiers.
  9. Not understanding memory management: Be aware of how memory is allocated for structures in C++, including the stack and heap, and ensure you manage memory efficiently.
  10. Not using standard library functions effectively: Make use of standard library functions like std::sort() and std::getline() to simplify your code and improve its readability.

Practice Questions

  1. Create a structure named Employee with fields for name, ID, department, salary, and date of birth (using a struct tm object). Write a program that takes input for three employees and outputs their details using standard library functions.
  2. Modify the student management program to handle input errors (e.g., invalid age or GPA) and provide user feedback.
  3. Implement custom member initialization for the Employee structure, setting default values for each field.
  4. Add a function to calculate the total salary of all employees in the employee management program.
  5. Modify the employee management program to sort employees by department using the std::sort() function.
  6. Implement a function that calculates the average age of employees in the employee management program.
  7. Create a structure named Book with fields for title, author, publisher, publication year, and number of pages. Write a program that manages a library catalog using structures, allowing users to add, remove, and search books by title or author.
  8. Implement a function that calculates the total number of words in a book (assuming an average word length of 5 characters) given a Book structure.
  9. Modify the book management program to handle input errors (e.g., invalid publication year or page count) and provide user feedback.
  10. Implement custom member initialization for the Book structure, setting default values for each field.

FAQ

  1. Why use structures in C++? Structures allow you to group related variables together, making it easier to manage complex data. They also enable custom data types that can be tailored to specific needs. Additionally, they provide a way to create user-defined data types before the introduction of classes in C++.
  2. How is memory allocated for structures in C++? Memory for each field in a structure is allocated sequentially when the structure is created. The size of the structure is equal to the sum of the sizes of its individual fields. Structures are stored on the stack by default, but can be dynamically allocated on the heap using new and deallocated using delete.
  3. Can I access structure fields using pointers? Yes, you can access structure fields using pointers by dereferencing the pointer and using the dot operator (.). However, it's generally recommended to use the dot operator for readability and ease of use. You can also use pointers to dynamically allocate structures on the heap.
  4. What are some benefits of custom member initialization in structures? Custom member initialization allows you to set default values for structure members, making it easier to ensure that all members are properly initialized and reducing the need for manual initialization code. It also makes your code more concise and easier to read.
  5. Why should I avoid using old-style character arrays in C++? Old-style character arrays, such as char name[50], are not null-terminated and can lead to issues when working with strings. Using standard library string types like std::string provides a more solid approach for handling strings in C++.
  6. How can I create a structure that contains another structure? You can create a structure that contains another structure by declaring the nested structure within the outer structure. For example:
struct Address {
char street[50];
int houseNumber;
};

struct Person {
std::string name;
Address address;
};

In this example, we have created a Person structure that includes an Address structure as one of its fields.

  1. What is the difference between structures and classes in C++? Structures and classes are similar in that they both allow you to group related variables together. However, classes have private access specifiers by default, support inheritance, constructors, destructors, and operator overloading, while structures do not. Additionally, structures have public access specifiers by default.
  2. What is the difference between a structure and an array in C++? A structure groups related variables together under a single name, while an array stores multiple variables of the same type in contiguous memory locations. Structures can contain arrays as fields, but arrays cannot contain structures as elements.
  3. How can I pass a structure to a function in C++? You can pass a structure to a function by passing a reference or pointer to the structure. For example:
void printStudent(const Student &s) {
std::cout << "Name: " << s.name << "\n";
std::cout << "Age: " << s.age << "\n";
std::cout << "GPA: " << s.gpa << "\n";
}

int main() {
Student s;
// ... fill in student data ...
printStudent(s);
return 0;
}

In this example, we have defined a function printStudent() that takes a reference to a Student structure as its parameter. We then call this function with our Student variable s.

  1. How can I copy a structure in C++? You can copy a structure by creating a new instance of the structure and assigning each field of the original structure to the corresponding field of the new structure. For example:
struct Student {
std::string name;
int age;
float gpa;
};

Student copyStudent(const Student &s) {
Student result;
result.name = s.name;
result.age = s.age;
result.gpa = s.gpa;
return result;
}

int main() {
Student original;
// ... fill in student data for original ...
structure (C++) | C++ | XQA Learn