DEV Community 👩‍💻👨‍💻

Cover image for C++: A concise introduction to structures
Isaac Smith
Isaac Smith

Posted on

C++: A concise introduction to structures

A structure is a collection of variables of different data types stored in a block of memory under a single name, allowing the different variables to be accessed via a single pointer or by the struct declared name, which returns the same address. This is a convenient way to keep related information together. It is similar to a class in that both contain a collection of data of various datatypes. Structures are known as compound data types because they are made up of several different variables that are logically connected. By default, struct members in C++ are public. The general structure declaration format is

struct structureName {
    datatype member0;
    datatype member1;
    datatype member2;
};
Enter fullscreen mode Exit fullscreen mode

Memory is not allocated when a structure is created. After a variable is added to the struct, memory is allocated. The struct datatype cannot be treated like a built-in data type in C++. Inside the structure body, static members cannot be created. Constructors cannot be created within structures. The dot (.) operator is used to access structure members, and the arrow (→) operator is used to access structure members if we have a pointer to a structure.
Here's an example of a struct.

struct Album {
    string title;
    string artist;
    float cost;
    int quantity;
};

int main() {
    struct Album song;
    song.title = "Summer-The four seasons";
    song.artist = "Antonio Vivaldi";
    song.cost = 50.0
    song.quantity = 10000

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

The structure Album is declared here, which consists of four members: title, artist, cost, and quantity. A structure variable song is defined within the main function. The appropriate data is then entered into it.

Happy Coding.

Top comments (0)

🌙 Dark Mode?!

Turn it on in Settings