Back to C++
2026-01-137 min read

2. Structure (struct) (C++)

Learn 2. Structure (struct) (C++) step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on C++ structures! Understanding and mastering the art of data organization using structures in C++ is crucial for various reasons:

  1. Simplifying complex data management: Structures allow you to group related variables together under a single name, making it easier to handle complex data sets or records.
  2. Improving code readability and maintainability: By organizing your data effectively, you create more readable and maintainable code, which is essential for both coding interviews and real-world programming projects.
  3. Debugging complex code: Structures can help you identify and isolate issues in your code by providing a clear structure for data storage and access.
  4. Leveraging efficiency: Structures can be more efficient than using classes in some cases, as they do not support inheritance or polymorphism, which may not always be necessary.

Prerequisites

To fully grasp the concepts covered in this lesson, it's essential to have a solid foundation in:

  1. Basic C++ syntax and data types
  2. Object-oriented programming concepts (classes and objects)
  3. Understanding memory allocation and CPU usage in C++
  4. Familiarity with standard library headers such as ` and `
  5. Knowledge of control structures like loops and conditionals

Core Concept

In C++, structures (or structs) are user-defined data types that enable you to organize related variables under a single name. This feature is particularly useful when dealing with complex data sets or records where multiple pieces of information need to be stored and accessed as a unit.

Declaring a Structure

To create a structure, we use the struct keyword followed by the structure name and a pair of curly braces {}. Within these braces, we define the variables that make up the structure:

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

In this example, we've created a Student structure with three member variables: name, age, and gpa. Each variable has its own data type specified.

Accessing Structure Members

To access the members of a structure, you use the dot operator (.) followed by the structure name and the member variable name. For example:

Student student;
student.name = "John Doe";
student.age = 20;
student.gpa = 3.5;

Here, we've created a Student object named student, and assigned values to its member variables.

Initializing Structures

You can initialize structures using one of two methods: default initialization or explicit initialization.

  1. Default initialization: This method assigns default values (zero for numeric types, empty string for strings) to all members of the structure. For example:
Student student; // All member variables are initialized to their default values
  1. Explicit initialization: You can explicitly initialize a structure's member variables during declaration or assignment. For example:
Student student = {"John Doe", 20, 3.5}; // Explicitly initializing the Student structure

Structure Arrays

Just like with other data types, you can create arrays of structures to store multiple records. For example:

const int NUM_STUDENTS = 10;
Student students[NUM_STUDENTS]; // Creating an array of Student structures

Now you can access each student's information using the index operator ([]).

Structure Padding and Alignment

It's essential to understand that when you create a structure, the compiler may pad it with extra bytes to ensure proper alignment of its members. This padding is often necessary for performance reasons but can lead to unexpected behavior if not accounted for in your code. To mitigate this issue, you can use packing attributes (#pragma pack) or aligned new expressions (new char[n] alignas(type)).

Worked Example

Let's walk through a complete example that demonstrates working with structures in C++.

#include <iostream>
#include <string>

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

void printStudent(const Student& student) {
std::cout << "Name: " << student.name << "\n";
std::cout << "Age: " << student.age << "\n";
std::cout << "GPA: " << student.gpa << "\n\n";
}

int main() {
const int NUM_STUDENTS = 3;
Student students[NUM_STUDENTS] = {
{"John Doe", 20, 3.5},
{"Jane Smith", 19, 3.7},
{"Mike Johnson", 21, 3.8}
};

for (int i = 0; i < NUM_STUDENTS; ++i) {
printStudent(students[i]);
}

return 0;
}

In this example, we've created a Student structure and a function called printStudent() to print out a student's information. We then create an array of three students and loop through the array, calling the printStudent() function for each student.

Common Mistakes

  1. Forgetting to include necessary headers: Make sure you have included all required headers (e.g., ``) for your structures to work correctly.
  2. Incorrect structure declaration syntax: Ensure that you're using the correct syntax when declaring a structure, including the struct keyword and proper variable declarations within the curly braces.
  3. Accessing undefined structure members: Double-check that you've defined all structure members before attempting to access them.
  4. Incorrect initialization of structures: Make sure you're using either default or explicit initialization when creating structures, and be aware of the differences between the two methods.
  5. Misusing structure arrays: Remember that structure array indices start at 0, so be careful when accessing elements to avoid out-of-bounds errors.
  6. Structure padding and alignment issues: Be aware of structure padding and alignment, and use packing attributes or aligned new expressions if necessary to ensure proper behavior.
  7. Inconsistent case sensitivity: C++ is case sensitive, so be mindful of the case when accessing structure members and defining function parameters.
  8. Mixing up structure and class syntax: Remember that structures are declared with the struct keyword, while classes are declared with the class or interface keywords.
  9. Using uninitialized structures: Make sure to initialize your structures before using them to avoid undefined behavior.
  10. Incorrect use of pointer arithmetic: When working with structure arrays, be careful when using pointer arithmetic to ensure proper access to the correct structure member.

Practice Questions

  1. Create a Book structure with member variables for title, author, and publication year. Write a program that declares an array of five books and prints out their information.
  2. Modify the previous example to include a function that calculates the average GPA of all students in the students array.
  3. Add a new structure member called major to the Student structure, and modify the program to store and print this additional piece of information for each student.
  4. Write a function that sorts an array of Student structures based on their GPAs.
  5. Create a nested structure called Employee, which contains a Person (a structure with member variables name, address, and phone number) and a Salary (with member variables base salary and bonuses). Write a program that creates an array of five employees and prints out their information.
  6. Modify the previous example to include a function that calculates the total compensation for each employee (base salary + bonuses).
  7. Create a structure called Car with member variables make, model, year, and color. Write a program that declares an array of five cars and prints out their information.
  8. Modify the previous example to include a function that calculates the total number of cars manufactured by each make in the array.
  9. Create a structure called Product with member variables name, price, and quantity. Write a program that declares an array of five products and prints out their information.
  10. Modify the previous example to include a function that calculates the total revenue for all products in the array.

FAQ

  1. Why use structures instead of classes? Structures are more lightweight than classes in C++, as they do not support inheritance or polymorphism. However, they can still be useful for organizing data when these features are not necessary.
  2. Can I define a structure within another structure? Yes! This is called a nested structure and can be useful for representing complex data structures.
  3. How do I pass a structure as an argument to a function? To pass a structure as an argument, you simply include the structure name in the function's parameter list. For example:
void printStudent(Student student) {
// Function implementation
}

int main() {
Student student = {"John Doe", 20, 3.5};
printStudent(student);
}
  1. How do I return a structure from a function? To return a structure from a function, you can define the function's return type as the structure itself. For example:
struct Student {
// ...
};

Student getBestStudent(Student students[], int numStudents) {
// Function implementation to find and return the best student
}

int main() {
const int NUM_STUDENTS = 3;
Student students[NUM_STUDENTS] = { ... };
Student bestStudent = getBestStudent(students, NUM_STUDENTS);
}
  1. How do I copy a structure? To copy a structure, you can use the copy constructor or assignment operator. If neither is provided, C++ will generate a default one for you. For example:
struct Student {
// ...
Student(const Student& other) : name(other.name), age(other.age), gpa(other.gpa) {}
};

int main() {
Student student1 = {"John Doe", 20, 3.5};
Student student2 = student1; // Copying student1 to student2 using the copy constructor
}
  1. How do I move a structure? To move a structure, you can use the move constructor or assignment operator if they are provided. For example:
struct Student {
// ...
Student(Student&& other) : name(std::move(other.name)), age(other.age), gpa(other.gpa) {}
};

int main() {
Student student1 = {"John Doe", 20, 3.5};
Student student2; // Creating an empty student2 to move student1 into it
student2 = std::move(student1); // Moving student1 into student2 using the move constructor
}
  1. How do I overload operators for structures? You can overload operators like ==, !=, <, >, etc., for your structures to provide custom comparison or arithmetic behavior. For example:
struct Student {
// ...
bool operator==(const Student& other) const {
return name == other.name && age == other.age && gpa == other.gpa;
}
};

int main() {
Student student1 = {"John Doe", 20, 3.5};
Student student2 = {"John Doe", 20, 3.5};
if (student1 == student2) {
std::cout << "Students are equal.\n";
} else {
std::cout << "Students are not equal.\n";
}
}
2. Structure (struct) (C++) | C++ | XQA Learn