Structures in C++ are user-defined data types that allow you to combine different types of data into a single unit. They are useful for organizing related information together.
What is a Structure?
A structure (struct) is a collection of variables of different data types grouped under one name.
For example, a student may have:
- Name
- Age
- Marks
Instead of creating separate variables, a structure stores them together.
Why Use Structures?
Structures are useful because they:
- Organize related data
- Reduce code complexity
- Improve readability
- Represent real-world entities
Syntax of Structure
struct StructureName {
data_type member1;
data_type member2;
};
Example of Structure
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float marks;
};
int main() {
Student s1;
s1.name = "Ali";
s1.age = 18;
s1.marks = 85.5;
cout << s1.name << endl;
cout << s1.age << endl;
cout << s1.marks << endl;
return 0;
}
Output
Ali
18
85.5
How Structures Work
structdefines a custom data type- Variables inside structure are called members
- Structure variables are called objects
- Members are accessed using the dot (
.) operator
Accessing Structure Members
s1.name = "Ali";
Structure Initialization
You can initialize structure values directly.
Student s1 = {"Ahmed", 20, 90.5};
Array of Structures
Structures can also be used in arrays.
Student students[3];
Example of Array of Structures
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
int main() {
Student s[2];
s[0].name = "Ali";
s[0].age = 18;
s[1].name = "Ahmed";
s[1].age = 20;
cout << s[0].name << endl;
cout << s[1].name << endl;
return 0;
}
Nested Structures
A structure can contain another structure.
struct Address {
string city;
};
struct Student {
string name;
Address addr;
};
Structure with Functions
Structures can also contain functions in C++.
struct Demo {
int x;
void show() {
cout << x;
}
};
Difference Between Structure and Class
| Structure | Class |
|---|---|
| Members are public by default | Members are private by default |
| Mainly used for simple data grouping | Used for full OOP concepts |
Advantages of Structures
- Easy data organization
- Supports different data types together
- Improves code clarity
- Useful for records and databases
Why Structures are Important
Structures are important because they:
- Represent real-world objects
- Help manage complex data
- Support better program design
- Form the base of advanced concepts
Real-Life Example
Think of a student ID card:
- Name
- Roll number
- Class
- Marks
All related information is stored together, just like a structure.
Conclusion
Structures in C++ are powerful user-defined data types used to group related data together. They improve program organization, readability, and efficiency, making them essential for handling complex information in real-world applications.