In this tutorial, we'll explore the concept of structures in C++, which are a powerful way to group related data together. Understanding how to define and use structures is crucial for organizing complex data models in your programs.
Structures allow you to create composite data types that can contain multiple variables (members) of different types. This makes it easier to manage related data as a single unit, similar to how you might organize your belongings into different drawers or boxes. Structures are especially useful when dealing with real-world entities that have multiple attributes.
To define a structure in C++, you use the struct keyword followed by the structure's name and a set of curly braces {} containing its members. Here's a simple example:
1#include <iostream>2using namespace std;34// Define a struct named 'Car'5struct Car {6string make;7string model;8int year;9};1011int main() {12// Create a variable of type 'Car'13Car myCar;1415// Assign values to the members16myCar.make = "Toyota";17myCar.model = "Corolla";18myCar.year = 2020;1920// Output the member values21cout << "Make: " << myCar.make << endl;22cout << "Model: " << myCar.model << endl;23cout << "Year: " << myCar.year << endl;2425return 0;26}
Make: Toyota Model: Corolla Year: 2020
In this example, we defined a structure named Car with three members: make, model, and year. We then created an instance of the Car structure called myCar and assigned values to its members. Finally, we printed out these values.
You can access the members of a structure using the dot operator (.). The dot operator is used to specify which member you want to access from a particular structure variable.
1#include <iostream>2using namespace std;34struct Car {5string make;6string model;7int year;8};910int main() {11Car myCar = {"Honda", "Civic", 2018};1213cout << "Make: " << myCar.make << endl;14cout << "Model: " << myCar.model << endl;15cout << "Year: " << myCar.year << endl;1617return 0;18}
Make: Honda Model: Civic Year: 2018
In this example, we initialized myCar with values directly in the declaration and accessed its members using the dot operator.
You can also create an array of structures, which is useful for managing multiple instances of a structured data type. Here's how you can do it:
1#include <iostream>2using namespace std;34struct Car {5string make;6string model;7int year;8};910int main() {11// Create an array of 3 Car structures12Car cars[3] = {13{"Ford", "Mustang", 2019},14{"Chevrolet", "Camaro", 2020},15{"Tesla", "Model S", 2021}16};1718// Loop through the array and print each car's details19for (int i = 0; i < 3; ++i) {20cout << "Car " << i + 1 << ": " << cars[i].make << ", "21<< cars[i].model << ", " << cars[i].year << endl;22}2324return 0;25}
Car 1: Ford, Mustang, 2019 Car 2: Chevrolet, Camaro, 2020 Car 3: Tesla, Model S, 2021
In this example, we created an array of Car structures and initialized it with three different cars. We then used a loop to iterate through the array and print out the details of each car.
Structures can also contain other structures as members. This is known as nested structures and is useful for modeling complex relationships between data types.
1#include <iostream>2using namespace std;34// Define a struct for Address5struct Address {6string street;7string city;8string state;9int zip;10};1112// Define a struct for Person that includes an Address13struct Person {14string name;15int age;16Address address; // Nested structure17};1819int main() {20// Create a Person and initialize its members, including the nested Address21Person person1 = {22"John Doe",2330,24{"123 Elm St", "Springfield", "IL", 62704}25};2627cout << "Name: " << person1.name << endl;28cout << "Age: " << person1.age << endl;29cout << "Address: " << person1.address.street << ", "30<< person1.address.city << ", "31<< person1.address.state << ", "32<< person1.address.zip << endl;3334return 0;35}
Name: John Doe Age: 30 Address: 123 Elm St, Springfield, IL, 62704
In this example, we defined a nested structure where the Person struct contains an Address struct as one of its members. We then created a Person instance and initialized all its members, including the nested Address.
While structures and classes in C++ are similar, there are some key differences:
class keyword with struct).Here's a comparison table:
| Feature | struct | class |
|---|---|---|
| Default Access | Public | Private |
| Inheritance | No (unless specified) | Yes |
| Purpose | Passive data storage | Active data and functions |
1#include <iostream>2using namespace std;34// Define a struct5struct Point {6int x;7int y;8};910// Define a class11class Rectangle {12private:13int width;14int height;15public:16void setDimensions(int w, int h) {17width = w;18height = h;19}20int area() {21return width * height;22}23};2425int main() {26Point p1;27p1.x = 3;28p1.y = 4;2930cout << "Point: (" << p1.x << ", " << p1.y << ")" << endl;3132Rectangle rect;33rect.setDimensions(5, 6);34cout << "Area of rectangle: " << rect.area() << endl;3536return 0;37}
Point: (3, 4) Area of rectangle: 30
In this example, we defined a Point structure and a Rectangle class. The Point struct has public members, while the Rectangle class has private members that can only be accessed through public methods.
Let's create a practical example where we manage a list of employees using structures. Each employee will have a name, ID, and department.
1#include <iostream>2using namespace std;34// Define an Employee struct5struct Employee {6string name;7int id;8string department;9};1011int main() {12// Create an array of 3 employees13Employee employees[3] = {14{"Alice", 101, "HR"},15{"Bob", 102, "Engineering"},16{"Charlie", 103, "Marketing"}17};1819// Loop through the array and print each employee's details20for (int i = 0; i < 3; ++i) {21cout << "Employee " << i + 1 << ": Name - " << employees[i].name22<< ", ID - " << employees[i].id23<< ", Department - " << employees[i].department << endl;24}2526return 0;27}
Employee 1: Name - Alice, ID - 101, Department - HR Employee 2: Name - Bob, ID - 102, Department - Engineering Employee 3: Name - Charlie, ID - 103, Department - Marketing
In this example, we defined an Employee structure and created an array of three employees. We then used a loop to print out the details of each employee.
struct keyword followed by its name and members..).Now that you understand how to define and use structures in C++, the next step is to learn about Structure and Function. This will help you write more modular and reusable code by passing structures as arguments to functions and returning them from functions.