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

C++ Structures

Learn C++ Structures step by step with clear examples and exercises.

Title: Mastering C++ Structures: A full guide for C++ Programmers

Why This Matters

Structures (struct) in C++ are a fundamental building block of object-oriented programming, allowing you to group related data and functions together. Understanding structures is crucial for writing efficient and maintainable code, especially when dealing with complex data structures like arrays, linked lists, and trees. Structures can also help you prepare for job interviews and real-world coding challenges by demonstrating your ability to organize and manipulate data effectively.

Prerequisites

Before diving into C++ structures, you should have a solid understanding of the following concepts:

  1. Basic C++ syntax (variables, operators, loops, functions)
  2. Object-oriented programming principles (classes, inheritance, polymorphism)
  3. Pointers and memory management in C++
  4. Standard Template Library (STL) containers like vectors and maps

Core Concept

A structure in C++ is a user-defined data type that allows you to define a collection of variables of different types under a single name. Structures are declared using the struct keyword, followed by the structure name and a pair of curly braces {}. Each variable within the structure is called a member, and can be accessed using the dot operator (.).

Here's an example of a simple structure that defines a person with first name, last name, and age:

struct Person {
std::string firstName;
std::string lastName;
int age;
};

In this example, Person is the structure name, and it has three members: firstName, lastName, and age. Each member is of a different data type (std::string for strings and int for integers).

To create an instance of the Person structure, you can use the following syntax:

Person person; // creates an empty Person struct
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;

In this example, we create a Person instance named person, and set its members to the desired values. You can access and manipulate the members of a structure just like you would with regular variables.

Worked Example

Let's consider a more complex example involving a Student structure that includes information about a student, such as their name, ID number, department, and semester GPA.

struct Student {
std::string name;
int idNumber;
std::string department;
double gpa;
};

int main() {
Student student1;
student1.name = "Alice";
student1.idNumber = 123456;
student1.department = "Computer Science";
student1.gpa = 3.8;

std::cout << "Student 1:\n";
std::cout << "Name: " << student1.name << "\n";
std::cout << "ID Number: " << student1.idNumber << "\n";
std::cout << "Department: " << student1.department << "\n";
std::cout << "GPA: " << student1.gpa << "\n\n";

Student student2;
student2 = student1; // copy constructor in action

student2.name = "Bob";
student2.idNumber = 789012;
student2.department = "Electrical Engineering";
student2.gpa = 3.5;

std::cout << "Student 2:\n";
std::cout << "Name: " << student2.name << "\n";
std::cout << "ID Number: " << student2.idNumber << "\n";
std::cout << "Department: " << student2.department << "\n";
std::cout << "GPA: " << student2.gpa << "\n\n";

std::cout << "Student 1 after copying:\n";
std::cout << "Name: " << student1.name << "\n";
std::cout << "ID Number: " << student1.idNumber << "\n";
std::cout << "Department: " << student1.department << "\n";
std::cout << "GPA: " << student1.gpa << "\n\n";

return 0;
}

In this example, we define a Student structure with four members (name, ID number, department, and GPA). We create two instances of the Student structure, manipulate their members, and print them to the console. Notice that when we copy student1 into student2, the copy constructor is invoked automatically by C++.

Common Mistakes

  1. Forgetting to include the necessary header files: Make sure you include any required header files for the data types used in your structure, such as ` for strings and ` for input/output operations.
  1. Not initializing structure members: If you don't initialize structure members explicitly, they will be set to default values (e.g., zero for integers and empty string for strings). This can lead to unexpected behavior in some cases.
  1. Accessing invalid structure members: Always ensure that you are accessing valid members of a structure. If you try to access an undefined member or a member that has not been initialized, your program will likely crash or produce incorrect results.
  1. Not understanding the copy constructor and assignment operator: When you create a new instance of a structure by copying another one (e.g., Student student2 = student1), the copy constructor is called automatically. Similarly, when you assign one structure to another (e.g., student2 = student1), the assignment operator is called. Understanding these operators and how they work can help you avoid common pitfalls.

Practice Questions

  1. Define a structure named Car that includes members for the car's make, model, year, and color. Write a program that creates an instance of the Car structure, sets its members, and prints them to the console.
  1. Modify the Student structure from the worked example to include additional members like the student's email address and phone number. Write a program that creates multiple instances of the modified Student structure, sets their members, and prints them to the console in a formatted table.

FAQ

  1. Can I nest structures in C++?

Yes, you can define one structure within another structure. This is called embedding or nested structures.

  1. How do I declare an array of structures in C++?

To declare an array of structures, use the following syntax: struct_name struct_array[array_size];. For example, to create an array of 10 Student structures, you would write: Student students[10];.

  1. What is the difference between a structure and a class in C++?

In C++, both structures and classes are user-defined data types that allow you to group related variables together. The main difference lies in their default access specifiers: structures have public members by default, while classes have private members by default (although you can change this using access specifiers like public, private, and protected).

  1. How do I overload operators for a structure in C++?

You can overload operators for a structure just like you would for a class. To do so, define the operator function outside of the structure definition and use the keyword this to refer to the current structure object. For example, to overload the + operator for the Student structure, you might write:

struct Student {
// ... (structure definition)
};

Student operator+(const Student& lhs, const Student& rhs) {
Student result;
// Implement the logic to add two students and store the result in the `result` structure
return result;
}
C++ Structures | C++ | XQA Learn