Structures in C++

A structure is a collection of data items grouped under one name where each variable or item in the structure is called a member of the structure. A structure is similar to a class because both can hold a collection of different data types.

In C++, a structure can contain two types of members:

  1. Data Member - Data Members are normal C++ variables. A structure can be created with variables of different data types like int, char float etc.
  2. Member Functions - Member Functions are normal C++ functions. Functions can also be included along with variables inside a structure declaration.

How to declare a structure in C++ programming?

A structure is defined using the struct keyword. The struct keyword defines a structure type followed by an identifier. Then inside the curly braces, we can declare one or more members of that structure.

Syntax

struct structure_name {
   data_type variable1
   data_type variable2

};

Here, the structure_name is the name of the structure and variable1 and variable2 are the C++ variables of different data types like int, char, float, etc.

Example

struct Book {
   int book_id;
   char title[70];
   char subject[120];
};

Here, Book is the structure name with three member variables: book_id, title, and subject.

How to Define a Structure Variable?

Structure members cannot be initialized with declaration. Once we declare a structure as above. We can define a structure variable as:


Book mybook;

Here, a structure variable mybook is defined which is of type structure Book. When a structure variable is defined, only then the required memory is allocated by the compiler.

Memory is not allocated, when a structure is created. The structure definition is only the blueprint for the creation of variables. You can consider it as a datatype.

For example, we define a boolean as below:


bool active;     

The bool specifies that variable active can only hold a boolean value.

How to access members of a structure?

The dot "." operator is used to access members of a structure. It is a period between the structure variable name and the structure member.

Program to illustrate struct in C++:


#include <iostream>
#include <cstring>

using namespace std;

struct Books
{
  int book_id;
  char title[70];
  char subject[120];
};

int main()
{
   struct Books mybook; // Declare mybook of type structure Book

   // book 1 specification
   mybook.book_id = 1;
   strcpy(mybook.title, "Learn C++ Programming Language");
   strcpy(mybook.subject, "C++");

   // Print mybook info
   cout << "mybook id : " << mybook.book_id << endl;
   cout << "mybook title : " << mybook.title << endl;
   cout << "mybook subject : " << mybook.subject << endl;

   return 0;
}
Output
mybook id : 1
mybook title : Learn C++ Programming Language
mybook subject : C++