Structures in C++

usmanmalik's Avatar author of Structures in C++
This is an article on Structures in C++ in C++.
If you are reading this tutorial on structures, you must be familiar with the basics of C++; you know what purpose do variables serve and what their different types are. If you are not familiar with variables and arrays in C++, I would suggest you to first learn these concepts in some of our other tutorials and then come back here to learn what is often referred as the prologue to object oriented programming. Yes, we are going to explain one of the most exciting and at the same time, advanced C++ concept, the Structures.

Variables are of a particular type and they can only store data of that particular type. For instance an “int” variable will always store an integer, a “char” can only store a character and float can only store a floating point number. If we wanted to store large number of integers or characters, we took help of arrays. Arrays had a potential problem; array can only store series of data of one type. For example, an integer array will store only integers. We want to store data of multiple types in a single data structure. Structure basically allows you to do this.

What are structures?



A Structure in C++ is the data structure which is capable of storing multiple data types. Structures are very near to classes in their functionality with only major difference is that members of structure are public by default and members of a class are private by default. Structures should be used when you want to store or retrieve information from the database or when you have multiple data types and you want to group them together.

A typical example of structure can be a computer or a laptop. Laptops have several characteristics or specifications as commonly referred. Laptop has a memory, storage, processor etc. Now memory is usually an integer i.e. 4 GBs, 8 GBs etc. Storage capacity is also an integers i.e. 500 GBs etc. But a processor is usually a floating data type i.e 3.2 Ghz, core 2 due. Now we have two integer types and one floating data type. We cannot store these three data types into one array. Here what should we do? We utilize structures to store such data.

Syntax of a Structure



In order to define a structure, we use the keyword “struct”. The laptop information can be defined inside a structure as:
Code: Cpp
struct laptop
{
    int memory;
    int space;
    float processor;
};
Now, pay attention to the above lines of code. In line 1, we wrote “struct”, when compiler reaches this line; it would know that he has to allocate memory for a structure now. Keyword “struct” is followed by the name of the structure which is laptop in this case. A structure can have any name other than keywords. The name of structure plays the similar role as the name of any variable type such as int, char etc. We will see this in our code example later on. After the keyword struct and name of the struct, you write all the variables within opening and closing braces. Remember, a semicolon is placed after the closing braces to mark the end of the structure.

Structure Memory



A point to ponder here is that how much memory does a structure occupy? The answer is: memory occupied by a structure is equal to sum of the memories occupied by all the members of the structure. In the laptop example, we had two integers and one float; both integer and float occupy 4 bytes (On a 32 bit system), hence total memory of the structure would be 12 bytes (4+4+4).

Creating and using a structure is basically a three step process.
  1. Define a structure
  2. Define Structure variable.
  3. Access the members of the structure through structure variable.
We will explain all of these three steps with the help of a code sample. See the code in Example1.

Note: This code has been written using visual C++ with Visual Studio 2010. This is a win 32 console application.

Example1
Code:
#include <iostream>
using namespace std;

struct laptop
{
     int memory;
     int storage;
     float processor;
}; 

int main()
{

	laptop lap1;
	lap1.memory = 4;
	lap1.storage = 500;
	lap1.processor = 3.2;

	cout<<"Laptop Memory: "<<lap1.memory<<" GBs."<<endl;
	cout<<"Laptop Storage Space: "<<lap1.storage<<" GBs."<<endl;
	cout<<"Laptop Processor: "<<lap1.processor<<" Ghz.";
}
In the Example 1, we have declared a structure laptop before the main method which is the step 1. The inside the main method, in the first line, we have defined a structure variable named “lap1”. Now if we want to access any member of this structure, we will access those members through this variable lap1.

After the structure variable definition, in the next three lines, we have accessed the structure members using dot operator. It is very important to note here that if you want to access the members of a structure, you can do so by writing structure’s variable name, followed by a dot operator and then the name of the variable you want to access as we have accessed memory by writing a statement like lap1.memory. This is the third step of defining and using a structure variable.

In Example1, we have simply stored three values in three members of the structures and then we have printed their values on the screen. The output of Example1 would be something like:

Output 1:



Member Initialization with Structure Variable Definition
In Example1 we saw that in the main function, first we defined the structure variable and then in the next three lines we initialized structure members with three different values. We can combine these two steps i.e. we can define the structure variable and initialize structure members in the same line. We can do this as

Code:
laptop lap1 =  {4, 500, 3.2};
Now pay attention to the above line. We defined a structure variable lap1 as we did before. After that we placed an equal to sign and then open and closed braces followed by a semicolon. Focus on the values inside the opening and closing braces. The first value is ‘4’. First value will initialize the first member of the structure which means that memory will be initialized with 4. Next we have written 500 which will initialized the second member of the structure i.e. storage and third member processor will contain 3.2. Remember the sequence here is very important; you must place the values that correspond to the data type of the member functions. For instance, you cannot place 3.2 in the beginning of the braces because the first member of the structure is memory which is of type int.

Assigning one structure to another



Just like you can assign one variable to another, you can assign one structure to another. When you assign one variable to another variable, values of the first variable are copied to second variable. Same is the case with structure. Assigning one structure to another is a very simple task and requires mere “equal to” operator. Following line of code explains this concept.

Code:
laptop lap1 =  {4, 500, 3.2};
Code:
laptop lap2 = lap1; // Assigning one structure variable to the other.
Now, all the values of the members of structure lap1 will be stored in the member variables of structure lap2.

These two concepts: member initialization with structure variable definition and assigning one structure values to other have been explained in Example2. We have modified Example1 to explain these two concepts.

Example2:
Code:
#include <iostream>
using namespace std;

struct laptop
{
	int memory;
	int storage;
	float processor;
};                // Step 1: Structure Declaration

int main()
{

	laptop lap1 = {4,500,3.2}; //Member Initialization with structure definition
 
	cout <<"Values of structure lap1." <<endl;
	cout<<"Laptop Memory: "<<lap1.memory<<" GBs."<<endl;
	cout<<"Laptop Storage Space: "<<lap1.storage<<" GBs."<<endl;
	cout<<"Laptop Processor: "<<lap1.processor<<" Ghz."<<endl;
	cout<<"\n***************************************"<<endl;

	laptop lap2;

	lap2 = lap1;
	cout<<"Lap1 copied into lap2"<<endl;
	cout<<"\n***************************************"<<endl;

	cout <<"Values of structure lap2"<<endl;
	cout<<"Laptop Memory: "<<lap2.memory<<" GBs."<<endl;
	cout<<"Laptop Storage Space: "<<lap2.storage<<" GBs."<<endl;
	cout<<"Laptop Processor: "<<lap2.processor<<" Ghz.";
}
Now you can see that in the beginning of the main function, we are defining a structure variable for laptop structure and at the same time we are initializing values of the member variables of the structure with 4 for memory, 500 for storage and 3.2 for processor. We are displaying all these three values in the next lines.

After that you can see in the main method that we have defined another variable of laptop structure named lap2. Using assignment operator we have assigned the values of lap1 into lap2 and then we have displayed the values of the member variables of structure lap2. Since lap2 contains the values of members of lap1, the output for lap2 member values will be same as shown in the output2.

Output2



Nested Structures



Structures have several advanced and exciting features. Nested structures are one of those features. In nested loops we defined loops inside loops; likewise in nested structures we define structures within a structure.

Imagine a restaurant have three branches. We want to calculate sale of each branch and then total income of all of these branches. Sales can be in dollars as well as in cents. In this scenario we can declare an outer structure named income and a sub structure named sale. In income structure we can nest three sale structures where each sales structure will further contain 2 members, dollars and cents. Example 3 explains this concept.

Example3
Code:
#include <iostream>
using namespace std;

struct sale // Inner Structure
{
	float dollar;
	float cents;
};                

struct income // Outer Strucure
{
	sale sale1;
	sale sale2;
};

int main()
{

	income total_income;

	total_income.sale1.dollar= 100.47;
	total_income.sale1.cents = 176;

	total_income.sale2.dollar=127.14;
	total_income.sale2.cents = 180;

	float total_sale1, total_sale2;

	total_sale1= total_income.sale1.dollar + total_income.sale1.cents/100;
	total_sale2= total_income.sale2.dollar + total_income.sale2.cents/100;

	cout <<"Total income of the restaurant is: "<< total_sale1 + total_sale2<<" dollars.";
}
Above code sample might look confusing at first but with little effort you can grasp the concept. Let us start from the beginning:

We have defined two structures, an inner structure, sale which contains two floating variables, dollar and cents, followed by an outer structure income. A rule thumb is to define the inner structures first followed by the outer structures.

Now come towards the main function, inside the main function we have defined structure variable total_income. Remember, we only have to define one outer structure in order to access all the inner structures. But a question here is how we can access the variables of the inner structure using outer structure. The answer is simple, inner structures are actually member variables of outer structure. Therefore in order to access inner structure, we will simply use ‘dot’ operator. So in order to access inner structure sale from the outer structure income, we can simple do something like:

total_income.sale1 ;

Here total income is the variable of the outer structure “income” whereas sale1 is the variable of the inner structure “sale”, defined inside the outer structure income.

Now in order to access members of inner structure, we can go one step down further and place another dot operator to access the member variables of the inner structure as follows

total_income.sale1.dollar;

Using this dot operator we can access member variable of inner structures of any depth. For example we can do something like

retaurant.room.window.area.length ;

Here we have four structures with area being the inner most structure, and we have accessed length which is the member variable of ‘area’ structure from the outer most structure which is restaurant using the dot operator.

Coming back towards the example3, we have initialized both the inner structures of total_income with some variables and then accessed those variables. Note in floating variable sale1, we have stored sum of the dollars and cents of the sale1 inner structure. We have converted cents into dollars by dividing them with hundred. In the end we have displayed the sum of two sales. The output of Example 3 is

Output3



Structures are extremely useful in the context of C++ programming. If you can grasp this concept well, you can easily understand object oriented programming which is the basis of all the modern programming platforms. In this tutorial we have come up with basic explanation of what structures are. For more such tutorials, keep visiting this site.