C++ Structures

Structure in C++ programming language groups logically related information of different data types under a single name.

A structure variable can store multiple variables of different data types. Each variable declared in structure is called member. All member variables of a structure are stored in contiguous memory locations.

Suppose, we want to store information about all employees of a company. We want to store following information for every employee:

Name (String)
Age (integer)
Department (String)
Salary (floating point number)

We can create a custom data type, which can store all related information of an employee under a single name. C++ programming language provide support for defining a custom data type(structure) which can encapsulate and store all related information about an employee.

By using a structure, we can store all the details an employee into a structure variable, and then we can define an array of structures to store details of all employees.


How to declare a structure in C++ programming

The struct Keyword is used to declare a structure type. Declaration of a structure specifies the format of the user defined data type. Like any other variables in C, a structure must be declared, before it's first use in program.

Syntax of Declaring a Structure
struct structure_name
{
    data_type variable_name1;
    data_type variable_name2;
    .
    .
    data_type variable_nameN;
};
  • struct keyword is used to declare a structure.
  • structure_name is the name of the structure. It is a valid C++ identifier.
  • data_type variable_name1; is member declaration statement. data_type is the type of member variable.
  • We can declare any number of member variables inside a structure.
  • A structure definition is only schema for creating variables. It specifies that what data a structure variable can store.
  • Declaring a structure alone will not create any variable or allocate any memory. Memory is allocated first time when a variable of structure type is declared.
  • Structure declaration ends with a semicolon(;).
For Example : Structure declaration to store employee details
struct employee
{
 char name[100];
 int age;
 char department[50];
 float salary;
};

How to define a structure variable

Once we declare the format of structure, We can define a variable of structure . There are two ways of declaring a structure variable:

Defining variables at the time of structure declaration.
For Example :
struct employee
{
    char name[100];
 int age;
 float salary;
 char department[50];
} employee_one;
variable employee_one is an instance of structure employee.
Defining variables after structure declaration.

The syntax of defining a structure variable is similar to the variable definition syntax of any basic data type in C++.

struct structure_name variable_name;
For Example :
struct employee employee_one;

How to initialize a structure variable

In C++, to initialize a structure variable We can specify initial values as a comma separated list of constants enclosed between curly braces. First value in the list gets assigned to first member of structure and second value of list gets assigned to second members of structure and so on.

struct employee
{
    char name[100];
    int age;
    float salary;
    char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};
We can also initialize structure variable after structure declaration.
struct employee employee_one = {"Jack", 30, 1234.5, "Sales"};

It is not compulsory to initialize all the member variables of a structure. Following statement initializes only name member of structure employee and remaining members gets initialized with zero(for integer and float) and NULL(for pointers and char).

struct employee
{
    char name[100];
    int age;
    float salary;
    char department[50];
} employee_one = {"Jack"};

Access Structure Member in C++

In C++, once a structure variable is defined we can access the member variables using member access operator(.) or dot operator. We cannot access members of a structure directly in any expression by specifying their name alone.

Syntax of accessing structure member using dot operator

structure_variable.member_name
For Example : We can access the member "age" of employee structure variable employee_one as
struct employee
{
    char name[100];
    int age;
    float salary;
    char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

int age = employee_one.age;

If you want to access age of structure variable employee_one and assign it 40 to it. You can do it as follows :

employee_one.age = 40;

Structure member variables are just like any other variable in C++. We can perform all valid input/output and arithmetic operations.


Accessing structure member using Arrow Operator(->)

If you have a pointer to a structure variable, then you cannot use dot operator to access it's member variable. C++ programming language provides a structure pointer operator(or Arrow operator) to access members of structure using pointer variable. Here is the syntax of accessing member variable using structure pointer.

structure_pointer->member_name;

Structure pointer variable followed by an arrow operator and then the name of the member variable.

For Example :
struct employee
{
 char name[100];
 int age;
 float salary;
 char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

struct employee *ptr = &employee_one;
int age = ptr->age;

C++ Program to Access Structure Members Using Dot and Arrow Operator

#include <iostream>
using namespace std;

// Declaration of employee structure 
struct employee {
 char name[100];
 int age;
 float salary;
 char department[50];
};
 
int main(){
   struct employee EMP, *ptr;
    
   cout << "Enter Name, Age, Salary and Department of Employee\n";
   // Assigning data to members of structure variable
   cin >> EMP.name >> EMP.age >> EMP.salary >> EMP.department;
 
   // Printing structure members using dot operator
   cout << "\nEmployee Details\n";
   cout << "Name : " << EMP.name << "\nAge : "<< EMP.age <<
       "\nSalary : "<< EMP.salary << "\nDepartment : "<< EMP.department;
        
   // Printing structure members using arrow operator
   ptr = &EMP;
   cout << "\n\nEmployee Details\n";
   cout << "Name : " << ptr->name << "\nAge : "<< ptr->age << 
       "\nSalary : "<< ptr->salary << "\nDepartment : "<< ptr->department;


   return 0;
}

Program Output
Enter Name, Age, Salary and Department of Employee
Andy 22 2345 SDE

Employee Details
Name : Andy
Age : 22
Salary : 2345
Department : SDE

Employee Details
Name : Andy
Age : 22
Salary : 2345
Department : SDE

Best Practices of Using Structures in C++

  • Use Structures for Logical Grouping : Structures are ideal for logically grouping related data. Use them to represent entities with multiple attributes, improving code organization.

  • Initialize Structures : Always initialize structure members, especially when creating instances. This ensures predictable behavior and avoids potential issues with uninitialized data.

  • Consider Pointers for Dynamic Allocation : When dealing with a large number of instances or dynamic data, consider using pointers to structures for efficient memory management.

  • Leverage Nested Structures for Hierarchy : Utilize nested structures to represent hierarchical relationships between different components of your data.

  • Use Structures for Functionality : Structures can encapsulate not only data but also member functions, allowing for a more object-oriented approach in C++.

  • Validate Structure Comparisons : When comparing structures, ensure that each member is individually compared to avoid unexpected results.

  • Exercise Caution with Unions : Unions can be powerful but require careful use. Ensure that the union is used appropriately based on the context of your data.