x

C++ Structures

PREV     NEXT

What are Structures?

  • In C++, structure is a combination or group of different data elements that are grouped together under a single name.
  • The data elements are known as data members who have different data type and length.
  • It is a user defined data type that allows you to combine data items of different kinds.
  • The structures are used to define records like of we want to display employee records or student record.

Suppose if we want to keep the record of an employee than the attributes we need are:

  • Employee Name
  • Employee Code
  • Designation
  • Salary

How to define a structure?

  • To define the structure you need to use the struct statement. The struct statement defines different data type for different data members.

Let us have a look at the syntax that how the structure is declared:

For example:

In the above example, we have defined the data members with the size given in array.


How to access the data members of structure?

  • You can access any data member of a structure by using the member access operator (.).
  • The member access operator is valid between the structure name and the structure member that are to be accessed. And to define variables you will use struct keyword.

Let us have a look at the example:

  // employee 1 details

   strcpy( Emp1.Name, “ABC”);

   strcpy( Emp1.Designation, “Manager”);

   Emp1.Code = 6495;

   Emp1.Salary = 40000;

   // employee 2 details

   strcpy(Emp2.Name, “XYZ”);


   strcpy(Emp2.Name, “Analyst”);

   Emp2.Code = 6467;

   Emp2.Salary = 20000;

Advantages of Structures

The advantages of structures in C++ are:

  • The structure data members are public by default.
  • It is backwardly-compatible with C code.

What are Nested Structures?

  • Nested Structures are those where you declare structure within structure. A structure includes another structure like its member.

For example,

  • you have two structures Subjects and Student. To make Subjects nested to Student, you have to declare Subjects structure before and outside Student structure and create an object of Subjects structure inside Student structure.

Let us have a look at the example:

Array of Structures

  • As studied above that structure is a collection of different data type and an object of structure represents a single record in memory.
  • So, if you want to add more records of structure type than you have to create an array of structure or object. As you know the array is a collection of similar data type therefore, array can be of structure type.

Let us have a look at the example:

Pointers to Structures

As we have pointers to int, char, float and other data types, in the same way you have the pointers pointing to structures. And these pointers are known as structure pointers.

Let us have a look at the example:

PREV     NEXT



Like it? Please Spread the word!