A structure is a collection of variables of different data types and member functions under a single name.
It is similar to a class as both hold a collection of data of different data types.
Suppose you want to store some information about a person: their first_name
, last_name
, age
, and salary
.
You can easily create different variables—first_name
, last_name
, age
, salary
—to store this information separately.
However, in the future, you might want to store information about multiple people.
Now, you'd need to create different variables for each information per person:
first_name1, last_name1, age1, salary1, first_name2, last_name2, age2, salary2, …
You can visualize how big and messy the code would look. Additionally, as there is no relation between the variables (information), it would be a daunting task to manage.
A better approach is to have a collection of all related information under a single name, such as Person and use it for every individual.
Now, the code looks much cleaner, more readable, and efficient as well.
This collection of all related information under a single name Person is a structure.
The struct
keyword defines a structure type followed by an identifier (name of the structure).
Then, inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure. For example:
struct Person
{
string first_name;
string last_name;
int age;
float salary;
};
Here, the structure Person is defined which has four members: first_name
, last_name
, age
, and salary
.
When a structure is defined, no memory is allocated.
The structure definition is only the blueprint for the creation of variables. You can imagine it as a data type.
When you define an integer as below: