Zone Of Makos

Menu icon

Structures in C++

In C++, a structure is a user-defined data type that allows you to combine different types of variables under a single name. Structures provide a way to group related data together, making it easier to organize and manipulate complex data structures. In this lesson, we'll explore how to define and use structures in C++ and understand their role in creating custom data types.

Defining a Structure

To define a structure in C++, you use the struct keyword followed by the structure name and a set of braces. Inside the braces, you declare the members of the structure, which can be of different data types. Each member is defined similarly to a variable declaration.


struct Person {
    std::string name;
    int age;
    char gender;
};

// Creating an instance of the structure
Person person1;

Accessing Structure Members

You can access the members of a structure using the dot operator ( . ). The dot operator allows you to access or modify the individual members of the structure.


person1.name = "John Doe";
person1.age = 25;
person1.gender = 'M';

Structures as Function Parameters

You can pass structures as function parameters in C++. This allows you to operate on the structure members within the function.


void printPersonDetails(const Person& person) {
    std::cout << "Name: " << person.name << std::endl;
    std::cout << "Age: " << person.age << std::endl;
    std::cout << "Gender: " << person.gender << std::endl;
}

printPersonDetails(person1);

Nested Structures

Structures can be nested within other structures, allowing you to create more complex data structures.


struct Address {
    std::string street;
    std::string city;
    std::string state;
};

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

Employee employee1;
employee1.name = "Jane Smith";
employee1.address.street = "123 Main St";
employee1.address.city = "New York";
employee1.address.state = "NY";

Conclusion

Structures in C++ provide a way to group related data together and create custom data types. They allow you to organize and manipulate complex data structures more effectively. By defining structures, accessing structure members, passing structures as function parameters, and creating nested structures, you can leverage the power of structures to build more expressive and flexible programs in C++. Structures are an essential feature of the language and play a crucial role in designing and implementing data structures and objects.