Structures in C++

In this Tutorial we will study and understand the concept of Structures in C++ and:

  • Concept and Uses of Structures
  • Defining a Structure using struct keyword
  • Accessing the member values using . operator
  • Array of Structures
  • Passing Structure as arguments to a function
Concept and Uses of Structures in C++

A Structure in C++ is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. It is a user defined data type which allows you to combine data items of different kinds.

 

Structures in C++ Programming

Imagine you want to store details of a person for e.g. his name, age, height, date of birth and weight. In a typical scenario you will have to create 5 variables to store these values, but what if you have to store details of 20 people. Then you will have to create 100 variables and that will be very tedious and inefficient. In such scenarios we can create a struct datatype named Person and include all the details as member variables of this datatype to create a custom datatype. We can then simply create 20 variables of this new structure datatype or a single array of size 20.

Defining a Structures in C++

To define a structure, you must use the struct keyword. The struct statement defines a new data type, with more than one member, for your program. Following is the syntax for creating a structure in C++

Example of structure Definition

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access.

Example of Accessing members of a structure
Sample Program of Structures in C++

Run Online

Output
Enter Full name: Jim Morris
Enter age: 33
Enter Salary: 55000

Displaying Information.
Name: Jim Morris
Age: 33
Salary: 55000

Array of Structures

Because structures are types, they can also be used as the type of arrays to construct tables or databases of them:

Sample Program of Array of Structures in C++

Run Online

Output
Customer-1 ID: 25
Customer-1 Name: Bob Jones
Customer-2 ID: 26
Customer-2 Name: Jim Smith
Passing Structure as arguments to a function

You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example:

Run Online

Output
Book title : C++ Tutorials
Book author : Simple Snippets
Book subject : C++ Programming
Book id : 21231
Book title : PHP programming
Book author : Jon Dough
Book subject : PHP
Book id : 6495
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *