What is structure in C++


In C++, a structure (struct) is a user-defined data type that allows you to combine data items of different kinds. Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book: title, author, and ISBN.

Let’s use the example of a Car to illustrate how structures work in C++. We’ll define a Car structure with several attributes: make, model, year, and color.

#include <iostream>
using namespace std;

// Define the Car structure
struct Car {
    string make;
    string model;
    int year;
    string color;
};

int main() {
    // Create an instance of Car
    Car myCar;

    // Assign values to the fields of myCar
    myCar.make = "Toyota";
    myCar.model = "Corolla";
    myCar.year = 2020;
    myCar.color = "blue";

    // Print the information about myCar
    cout << "Car Details:" << endl;
    cout << "Make: " << myCar.make << endl;
    cout << "Model: " << myCar.model << endl;
    cout << "Year: " << myCar.year << endl;
    cout << "Color: " << myCar.color << endl;

    return 0;
}

In this example, Car is a structure containing four members: make, model, year, and color. In the main function, we create an instance of Car named myCar and assign values to its members. Finally, we print out these values.

Structures in C++ can also contain functions as members, but this is more commonly done using classes. The primary difference between structures and classes in C++ is that in a structure, members are public by default, whereas in a class, members are private by default. This means that, by default, the data in a structure is accessible to any part of the program, whereas the data in a class is only accessible to the class’s own methods or friend functions unless specified otherwise with public or protected access modifiers.