Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Suppose you are a car garage owner and you want to maintain a record of each car in your garage. You want to store the color, engine capacity, and model of each vehicle. How will you accomplish this? Note that Arrays in C + + are not going to help you, as they store data of the same type. Here, the problem is that the color will be a string and engineCapacity will be an integer. So structures in C++ come here for your rescue.
What are Structures in C++?
Structures in C++ are user-defined data types that allow developers to group multiple related variables under a single name. Each variable within a structure is called a member, and these members can be of different data types, such as integers, floats, or even other structures.
Structures enhance code organization by enabling the encapsulation of related data, making programs easier to understand and maintain. They are particularly useful for representing complex data models, like representing a point in 2D space with x and y coordinates or defining a student record with attributes like name, age, and GPA.
A structure is created using a keyword struct. Structures in C++ can contain:
Data Members:- These are normal variables in C++
Member Functions:- These are normal functions in C++
struct Employee {
string name;
int age;
float salary; };
Note: Always end structure definition with a semicolon, as shown above.
Let’s move towards understanding member functions inside structures in C++, it is worth noting that structures defined in C cannot have member functions, however, structures in C++ allow having member functions along with data members.
struct Employee { // Data Members
string name;
int age;
float salary;
// Member functions (Only in C++)
void display(){
cout << “The employee age is: ” << age;
} };
Now to make use of this structure, we have to make structure variables, but before that, I want to share an important concept i.e.No memory is allocated when you create a structure. Now you must be wondering why it is so? Let me clarify this here, see structures in C++ are like the blueprint for variable creation. Space will be allocated only when you create structure variables.
How to make Structure Variables?
In C++ you can define structure Variables in two ways:-
Define a structure variable in a separate declaration like you define primitive data type variables in C++.
struct Employee{ string name; int age; float salary;};
struct Employee e1;
Note: In C++, writing struct keyword before the declaration of a variable is optional i.e., we can also write Employee e1; instead of struct Employee e1;
The second way is to define a structure variable is defining them at the time of structure declaration:
struct Employee{ string name; int age; float salary;}e1; //variable is declared with Employee
You can define as many structure variables as you want. Suppose you want to store information of 5 Employees, then you can make five structure variables. Now we’ve learned to define structure variables, so next, we should learn about accessing the data members inside structures using these structure variables.
How to declare structure variables?
To declare structure variables, you first define the structure using the struct keyword, then create variables of that structure type. You can declare multiple variables in a single line or one at a time.
Code Implementation:
C++
C++
#include <iostream> #include <string>
struct Book { std::string title; std::string author; int publicationYear; float price; };
int main() { // Declaring structure variables Book book1; // Declare a single variable Book book2; // Declare another variable
Book 1:
Title: 1984
Author: George Orwell
Publication Year: 1949
Price: $15.99
Book 2:
Title: To Kill a Mockingbird
Author: Harper Lee
Publication Year: 1960
Price: $10.99
How to Access Members of a Structure?
The dot operator(.) is used in C++ to access structure members i.e the data members and member functions. Suppose you want to access the age of an employee, then you can write e1.age;
You can also assign a value using a dot operator like e1.age = 30;
We can initialize structure variables without using the dot operator also. Let’s see programs by both ways to initialize structure variables.
C++
C++
// C++ program using dot operator #include <iostream> #include <string> using namespace std;
// Creating a structure named Employee struct Employee { string name; int age; float salary;
So, from the above two codes, you’ve mastered two ways of initializing variables in the structures in C++. One way is to initialize the variables using dot operator and the second way is without using dot operator but here, with the second method, you need to be careful with the order of values you are passing.
Values should be passed in the same order as you have defined variables in the structure otherwise you will get unexpected results. Now let’s discuss structure pointers.
Pointers To Structure in C++
In C++, you must have worked with pointer variables for primitive data types like int, float, and char in C++. We can also make pointers for user-defined data types like structures here. Before moving forward, if you want to know more about pointers, then have a look here.
Let’s see a program where we will make a pointer variable to a structure:
#include <iostream>
using namespace std;
struct Employee {
string name;
int age;
float salary; };
int main(){
Employee* e;
return 0; }
In this program, we created a pointer e of user-defined data type Employee. To access data members with a pointer, you have to use the arrow operator (->) instead of dot operator(.)
Let’s modify the program discussed above using pointers so that it can become crystal clear to you.
C++
C++
#include <iostream> #include <string> using namespace std;
// Defining the Employee structure struct Employee { string name; int age; float salary; };
int main() { // Dynamically allocating memory for an Employee object Employee* e1 = new Employee;
// Getting input from the user cout << "Enter your name: "; cin >> e1->name; // Using arrow operator to access members cout << "Enter your age: "; cin >> e1->age; cout << "Enter your salary: "; cin >> e1->salary;
So in this program, you first created a structure pointer and then used that to access structure members.
How to initialize structure members?
Structure members can be initialized in several ways in C++. Here are three common methods: using a constructor, using an initialization list, and directly initializing during declaration.
Code Implementation:
C++
C++
#include <iostream> #include <string> using namespace std;
// Defining the Employee structure struct Employee { string name; int age; float salary;
// Constructor to initialize members Employee(string n, int a, float s) : name(n), age(a), salary(s) {} };
int main() { // Method 1: Using a constructor to initialize members Employee e1("Rahul", 30, 60000.50);
// Method 2: Using an initialization list during declaration Employee e2 = { "Rohit", 25, 50000.00 };
// Method 3: Direct assignment after declaration Employee e3; // Declare without initialization e3.name = "Mohit"; // Assigning values to members e3.age = 28; e3.salary = 55000.75;
We need structures to store variables of different data types in a single container. Unlike arrays in C++, Structures in C++ can store int value, float value, or whatever data type you want to keep.
How are structures in C++ different from classes in C++?
The significant difference between classes and structures in C++ is from a security perspective. By default, class members have private access specifiers, but structure members have public access specifiers by default. Another difference is that the class needs to have a constructor and a destructor, whereas there is no such need for structures in C++.
What is the benefit of struct in C++?
The benefit of using structures in C++ lies in their ability to group related data items of different types into a single unit, enhancing code organization, readability, and maintainability. They also facilitate better data modeling for complex entities.
Can I have an array of structures?
Yes! You can. The structure is just another user-defined data type and we can do the same things with structs as we do with primitive data types.
Conclusion
In this blog, we have discussed structures in C++. They are a powerful tool for organizing and managing related data. By allowing the grouping of different data types under a single name, structures enhance code clarity and facilitate better data modeling. They serve as a foundation for more complex data structures, making them essential in both simple and advanced programming tasks.
Live masterclass
Amazon PowerBI & AI Essentials: Data Visualization Tips
by Abhishek Soni
15 May, 2025
01:30 PM
Amazon SDE Resume Tips: Get Noticed, Get Hired
by Shantanu Shubham
12 May, 2025
01:30 PM
Microsoft Data Analytics Interview: How to Clear It?
by Prerita Agarwal
13 May, 2025
01:30 PM
Ace Data Interviews: Master Analytics with AI Tools
by DP Aurosish
17 May, 2025
07:30 AM
Crack Google SDE Interviews: Strategies to Master DSA
by Saurav Prateek
14 May, 2025
01:30 PM
Amazon PowerBI & AI Essentials: Data Visualization Tips