In this C++ tutorial, you will learn about Structures, declaring a Structure, how to declare Structure Variable and how to access the structure members in C++.
What is a Structure?
A structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name.
How to declare and create a Structure
Declaring a Structure:
The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces “{“and “}”. Finally, the closed braces end with a semicolon denoted as “;” following the statement. The above structure declaration is also called a Structure Specifier.
Example:
Three variables: custnum of type int, salary of type int, commission of type float are structure members and the structure name is Customer. This structure is declared as follows:
In the above example, it is seen that variables of different types such as int and float are grouped in a single structure name Customer.
Arrays behave in the same way, declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure.
After declaring the structure, the next step is to define a structure variable.
How to declare Structure Variable?
This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name.
In the above example, structure variable cust1 is defined as:
What happens when this is defined? When a structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type int and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allocate 2bytes for custnum, 2 bytes for salary and 4 bytes for commission.
How to access structure members in C++?
To access structure members, the operator used is the dot operator denoted by (.). The dot operator for accessing structure members is used thusly:
structure_variable_name.member_name
For example:
A programmer wants to assign 2000 for the structure member salary in the above example of structure Customer with structure variable cust1 this is written as: