struct StructureName {
data_type member1;
data_type member2;
data_type member3;
};Structures in C++: Building Custom Data Records With struct
Direct Answer & Core Concept
In C++, variables are used to store individual values such as integers, floating-point numbers, characters, and strings. However, real-world applications often need to store several related values together.
For example, a student record may contain:
Student ID
Student name
Age
Marks
Grade
Creating separate variables for every student can make a program difficult to manage. C++ provides a feature called structures (struct) that allows you to group related variables of different data types under one name.
Detailed Explanation & Mechanics
1. What Is a Structure in C++?
A structure is a user-defined data type that groups multiple related data members under a single name.
Each member can have a different data type.
For example, a student structure can store an ID, name, age, and marks.
Syntax of a Structure
Here:
structis the keyword used to declare a structure.StructureNameis the name of the structure.member1,member2, andmember3are its data members.The semicolon after the closing brace is required.
Example: Create a Student Structure
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
int age;
float marks;
};
int main() {
return 0;
}In this example, Student is a user-defined type containing four members:
| Member | Data type | Purpose |
|---|---|---|
id | int | Stores student ID |
name | string | Stores student name |
age | int | Stores student age |
marks | float | Stores student marks |
Declaring a structure defines a type. It does not automatically create a student record object.
2. Declaring Structure Variables
After defining a structure, you can create variables of that structure type.
Syntax
StructureName variableName;Example:
Student student1;
Student student2;Both variables contain their own copies of the structure members.
You can also declare multiple variables of the same structure type:
Student student1, student2, student3;Example: Declare and Display a Structure Variable
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
int age;
};
int main() {
Student student1;
student1.id = 101;
student1.name = "Rahul";
student1.age = 20;
cout << "Student ID: " << student1.id << endl;
cout << "Name: " << student1.name << endl;
cout << "Age: " << student1.age << endl;
return 0;
}Output:
Student ID: 101
Name: Rahul
Age: 20The program creates a structure variable named student1 and assigns values to its members.
3. Accessing Structure Members Using the Dot Operator
The dot (.) operator is used to access individual members of a structure variable.
Syntax
variableName.memberName;Example:
student1.id = 101;
student1.name = "Rahul";
student1.age = 20;You can also read and display individual members:
cout << student1.id;
cout << student1.name;The dot operator is used when you have a structure object or reference.
4. Initializing a Structure in C++
You can assign values to structure members when creating a structure variable.
Example 1: Aggregate Initialization
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
int age;
};
int main() {
Student student1 = {101, "Rahul", 20};
cout << student1.id << endl;
cout << student1.name << endl;
cout << student1.age << endl;
return 0;
}Output:
101
Rahul
20The values are assigned in the order in which the members are declared.
Example 2: Initialize With Default Member Values
You can provide default values directly in the structure definition.
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id = 0;
string name = "Unknown";
int age = 18;
};
int main() {
Student student1;
cout << student1.id << endl;
cout << student1.name << endl;
cout << student1.age << endl;
return 0;
}Output:
0
Unknown
18Default member initializers are used when a member is not otherwise initialized.
Example 3: Initialize Selected Members Using Designated Initializers
C++20 supports designated initializers for aggregates.
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
int age;
};
int main() {
Student student1 = {
.id = 101,
.name = "Rahul",
.age = 20
};
cout << student1.name;
return 0;
}Output:
RahulIn C++, designated initializers must follow the declaration order of the members.
5. Taking User Input in a Structure
You can use cin and getline() to receive values for structure members.
Example: Enter Student Details
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
int age;
float marks;
};
int main() {
Student student1;
cout << "Enter student ID: ";
cin >> student1.id;
cout << "Enter student name: ";
cin >> student1.name;
cout << "Enter age: ";
cin >> student1.age;
cout << "Enter marks: ";
cin >> student1.marks;
cout << "\nStudent Details" << endl;
cout << "ID: " << student1.id << endl;
cout << "Name: " << student1.name << endl;
cout << "Age: " << student1.age << endl;
cout << "Marks: " << student1.marks << endl;
return 0;
}Sample input:
101
Rahul
20
85.5Output:
Student Details
ID: 101
Name: Rahul
Age: 20
Marks: 85.5If you want to accept a full name containing spaces, use getline() instead of cin >> for the name.
For example:
cout << "Enter student name: ";
getline(cin >> ws, student1.name);The std::ws manipulator consumes leading whitespace, including a leftover newline, before reading the name.
6. Modifying Structure Members
Structure members can be modified after the object has been created.
Example
#include <iostream>
#include <string>
using namespace std;
struct Employee {
int id;
string name;
double salary;
};
int main() {
Employee emp = {101, "Amit", 30000};
cout << "Old Salary: " << emp.salary << endl;
emp.salary = 45000;
cout << "Updated Salary: " << emp.salary << endl;
return 0;
}Output:
Old Salary: 30000
Updated Salary: 45000The assignment changes the salary member of the emp object.
7. Array of Structures in C++
An array of structures allows you to store multiple records of the same type.
For example, an employee management system may need to store information about many employees.
Syntax
StructureName arrayName[size];Example: Store Multiple Student Records
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
float marks;
};
int main() {
Student students[3] = {
{101, "Rahul", 85.5},
{102, "Amit", 90.0},
{103, "Priya", 92.5}
};
for (int i = 0; i < 3; i++) {
cout << "Student " << i + 1 << endl;
cout << "ID: " << students[i].id << endl;
cout << "Name: " << students[i].name << endl;
cout << "Marks: " << students[i].marks << endl;
cout << endl;
}
return 0;
}Output:
Student 1
ID: 101
Name: Rahul
Marks: 85.5
Student 2
ID: 102
Name: Amit
Marks: 90
Student 3
ID: 103
Name: Priya
Marks: 92.5Explanation:
Student students[3]creates an array containing three student records.students[0]accesses the first student.students[1]accesses the second student.students[i].nameaccesses the name of the selected student.
Arrays of structures are useful in student, employee, inventory, and customer management systems.
8. Nested Structures in C++
A nested structure is a structure declared as a member of another structure.
This is useful when a record contains another group of related information.
For example, an employee may have personal information and address information.
Example: Employee With Address Details
#include <iostream>
#include <string>
using namespace std;
struct Address {
string city;
string state;
int pinCode;
};
struct Employee {
int id;
string name;
Address address;
};
int main() {
Employee emp = {
101,
"Amit",
{"Kolkata", "West Bengal", 700001}
};
cout << "Employee ID: " << emp.id << endl;
cout << "Name: " << emp.name << endl;
cout << "City: " << emp.address.city << endl;
cout << "State: " << emp.address.state << endl;
cout << "PIN Code: " << emp.address.pinCode << endl;
return 0;
}Output:
Employee ID: 101
Name: Amit
City: Kolkata
State: West Bengal
PIN Code: 700001Here, Employee contains an Address structure as one of its members.
You can access nested members using multiple dot operators:
emp.address.city;9. Passing a Structure to a Function
You can pass a structure object to a function in C++ just like other variables.
There are three common techniques:
Pass by value.
Pass by reference.
Pass by constant reference.
9.1 Pass a Structure by Value
When a structure is passed by value, the function receives a copy of the object.
Changes made to that copy do not modify the original object.
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
};
void display(Student s) {
cout << "ID: " << s.id << endl;
cout << "Name: " << s.name << endl;
}
int main() {
Student student1 = {101, "Rahul"};
display(student1);
return 0;
}Output:
ID: 101
Name: Rahul9.2 Pass a Structure by Reference
Passing by reference allows a function to modify the original structure object.
#include <iostream>
#include <string>
using namespace std;
struct Employee {
int id;
string name;
double salary;
};
void updateSalary(Employee& emp) {
emp.salary = 50000;
}
int main() {
Employee emp = {101, "Amit", 30000};
updateSalary(emp);
cout << "Updated Salary: " << emp.salary;
return 0;
}Output:
Updated Salary: 50000The Employee& parameter refers to the original object.
9.3 Pass a Structure by Constant Reference
If a function only needs to read a structure, use a constant reference.
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
};
void display(const Student& s) {
cout << s.id << endl;
cout << s.name << endl;
}
int main() {
Student student1 = {101, "Rahul"};
display(student1);
return 0;
}Output:
101
RahulThis avoids copying the structure and prevents modification through the function parameter.
10. Returning a Structure From a Function
A C++ function can return a structure object by value.
This is useful when a function needs to create and return a complete record.
Example: Return Employee Details
#include <iostream>
#include <string>
using namespace std;
struct Employee {
int id;
string name;
double salary;
};
Employee createEmployee() {
Employee emp = {101, "Amit", 45000};
return emp;
}
int main() {
Employee emp = createEmployee();
cout << "ID: " << emp.id << endl;
cout << "Name: " << emp.name << endl;
cout << "Salary: " << emp.salary << endl;
return 0;
}Output:
ID: 101
Name: Amit
Salary: 45000Returning structures by value is a normal and safe C++ technique. Modern compilers can often eliminate unnecessary copies.
11. Pointers to Structures in C++
A pointer can store the address of a structure object.
When accessing structure members through a pointer, you can use the arrow (->) operator.
Syntax
pointerName->memberName;This is equivalent to:
(*pointerName).memberName;Example: Access Structure Members Using a Pointer
#include <iostream>
#include <string>
using namespace std;
struct Employee {
int id;
string name;
double salary;
};
int main() {
Employee emp = {101, "Amit", 45000};
Employee* ptr = &emp;
cout << "ID: " << ptr->id << endl;
cout << "Name: " << ptr->name << endl;
cout << "Salary: " << ptr->salary << endl;
return 0;
}Output:
ID: 101
Name: Amit
Salary: 45000The pointer ptr stores the address of emp. The arrow operator accesses its members.
12. Structure With Functions as Members
In C++, a structure can contain member functions in addition to data members.
This allows you to group related data and operations together.
Example: Structure With a Member Function
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
void display() {
cout << "ID: " << id << endl;
cout << "Name: " << name << endl;
}
};
int main() {
Student student1 = {101, "Rahul"};
student1.display();
return 0;
}Output:
ID: 101
Name: RahulThe display() function belongs to the Student structure and can access its members directly.
Structures can also contain constructors, operators, and other member functions.
13. Difference Between struct and class in C++
Both struct and class are used to define user-defined types in C++.
They support:
Data members.
Member functions.
Constructors and destructors.
Inheritance.
Access control.
Operator overloading.
The main language-level differences are their default access and inheritance rules.
| Feature | struct | class |
|---|---|---|
| Default member access | Public | Private |
| Default inheritance access | Public | Private |
| Member functions | Supported | Supported |
| Constructors | Supported | Supported |
| Inheritance | Supported | Supported |
| Operator overloading | Supported | Supported |
| Common convention | Simple data records | Encapsulated objects |
Example: struct
struct Student {
int id; // Public by default
};You can access the member directly:
Student s;
s.id = 101;Example: class
class Student {
int id; // Private by default
public:
void setId(int value) {
id = value;
}
};The private member cannot be accessed directly from outside the class. The public function provides controlled access.
Important: A C++ struct is not limited to storing data. It can provide the same general capabilities as a class.
14. Real-World Applications of Structures in C++
Structures are useful when a program needs to manage related information as a single record.
Common applications include:
Student Management Systems
Store student IDs, names, marks, grades, and other academic details.
Employee Management Systems
Store employee names, IDs, salaries, department information, and contact details.
Banking Applications
Represent account numbers, customer names, and account balances.
Inventory Management
Store product IDs, product names, prices, and stock quantities.
Library Management Systems
Represent books with titles, authors, ISBN numbers, and availability information.
Game Development
Represent positions, player statistics, coordinates, and game-related records.
15. Common Mistakes When Using Structures
Mistake 1: Forgetting the Semicolon
Incorrect:
struct Student {
int id;
string name;
}Correct:
struct Student {
int id;
string name;
};A structure definition must end with a semicolon.
Mistake 2: Accessing Members Without an Object
Incorrect:
Student.id = 101;Correct:
Student student1;
student1.id = 101;You need a structure object to access its non-static data members.
Mistake 3: Using the Wrong Member Operator
Use the dot operator for an object:
student1.id;Use the arrow operator for a pointer:
ptr->id;Mistake 4: Forgetting to Initialize Members
Local structure variables without an initializer may contain members with indeterminate values when those members are not initialized by default member initializers or constructors.
Initialize the object when appropriate:
Student student1{
}
;Value initialization initializes the members using their applicable initialization rules.
Mistake 5: Confusing struct With an Array
A structure groups different members into one record.
An array stores multiple elements of the same type.
For example:
struct Student {
int id;
string name;
};This defines one student record type.
Student students[10];This creates an array of ten student records.
16. Best Practices for Using Structures
Use meaningful structure names such as
Student,Employee, andProduct.Group only logically related information together.
Initialize structure objects before using their members.
Use
constreferences when passing large structures that do not need modification.Use ordinary references when a function must update the original object.
Use arrays or standard containers when managing multiple records.
Prefer
std::stringfor text rather than manually managed character arrays.Use private members and public functions when you need controlled access to data.
Keep structure definitions organized and reusable.
Consider a class when the type needs stronger encapsulation or complex behavior.
17. Frequently Asked Questions (FAQs)
1. What is a structure in C++?
A structure is a user-defined data type that groups related variables, possibly of different data types, under one name.
2. Which keyword is used to create a structure?
The struct keyword is used to define a structure in C++.
3. How do you declare a structure variable?
Use the structure type name followed by the variable name:
Student student1;4. How do you access structure members?
Use the dot (.) operator:
student1.id = 101;5. Can a structure contain different data types?
Yes. A structure can contain members such as int, float, double, char, std::string, arrays, and other structure types.
6. Can we create an array of structures?
Yes. You can create an array of structure objects:
Student students[10];7. Can a structure contain another structure?
Yes. This is called a nested structure. One structure can be declared as a member of another structure.
8. Can a structure be passed to a function?
Yes. A structure can be passed by value, by reference, or by constant reference.
9. Can a function return a structure?
Yes. A C++ function can return a structure object by value.
10. What is the difference between dot and arrow operators?
The dot operator (.) accesses a member through an object. The arrow operator (->) accesses a member through a pointer to an object.
11. Can a structure contain functions?
Yes. C++ structures can contain member functions, constructors, and other class-like features.
12. What is the difference between struct and class?
The main difference is default access: members of a struct are public by default, while members of a class are private by default. Their default inheritance access also differs.
Runnable Code Example: Structures in C++
C++20 / C++23#include <iostream>
#include <string>
// Plain Old Data (POD) / Aggregate struct
struct DatabaseRecord {
int recordId;
std::string tableName;
double queryLatencyMs;
void display() const {
std::cout << "[Record #" << recordId << "] Table: " << tableName
<< " | Latency: " << queryLatencyMs << " ms
";
}
};
int main() {
// Designated initializers (C++20)
DatabaseRecord record{1001, "users_auth", 1.42};
record.display();
std::cout << "DatabaseRecord Size: " << sizeof(record) << " bytes
";
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: What is struct memory padding and alignment in C++?
Q: What is an aggregate struct in C++?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
struct for passive Plain Old Data (POD) / Data Transfer Objects (DTOs).2. Use
class when enforcing invariants, private encapsulation, and complex behavior.3. Order struct data members from largest to smallest to minimize memory padding waste.