C++ Structures β A Complete Guide with Examples & Use Cases
Introduction β Why Learn C++ Structures?
In C++ programming, a structure (or struct) is a user-defined data type that allows grouping of variables under a single name. Itβs particularly useful for organizing complex data like employee records, coordinates, or student details.
In this guide, youβll learn:
- How to define and declare a structure
- Accessing and modifying structure members
- Nested and array of structures
- Passing structures to functions
- The difference between
structandclassin C++
Core Concept β What is a Structure in C++?
A structure groups related variables (of different types) under one name. Unlike arrays (same type) or simple variables (single data), structures hold diverse data conveniently.
struct Employee {
int id;
string name;
float salary;
};
Key Point: Unlike C, structures in C++ can have functions, constructors, access modifiers, and even inheritance.
Code Examples β With Step-by-Step Explanations
Example 1: Declaring and Using a Structure
#include <iostream>
using namespace std;
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
Student s1 = {101, "Alice", 89.5};
cout << "Roll No: " << s1.rollNo << endl;
cout << "Name: " << s1.name << endl;
cout << "Marks: " << s1.marks << endl;
return 0;
}
Explanation:
Studentis the structure names1is a structure variable- Members are accessed via dot
.operator
Output:
Roll No: 101
Name: Alice
Marks: 89.5
Example 2: Array of Structures
struct Product {
int id;
string name;
float price;
};
int main() {
Product items[2] = {{1, "Laptop", 45000}, {2, "Mouse", 500}};
for (int i = 0; i < 2; ++i) {
cout << items[i].id << " - " << items[i].name << " - βΉ" << items[i].price << endl;
}
return 0;
}
Output:
1 - Laptop - βΉ45000
2 - Mouse - βΉ500
Example 3: Passing Structures to Functions
struct Book {
string title;
float price;
};
void display(Book b) {
cout << "Title: " << b.title << ", Price: βΉ" << b.price << endl;
}
int main() {
Book b1 = {"C++ Basics", 299.99};
display(b1);
return 0;
}
Best Practice: Pass by reference (void display(Book &b)) to avoid data copy overhead.
Example 4: Structure with Member Functions
struct Rectangle {
int length, width;
int area() {
return length * width;
}
};
int main() {
Rectangle r1 = {10, 5};
cout << "Area = " << r1.area();
}
Output:
Area = 50
Best Practices & Tips
Best Practices:
- Use
typedeforusingfor long struct names. - Initialize members properly using constructors (if added).
- Keep functions inside structures short and focused.
Tips:
- Prefer
classoverstructwhen implementing complex behaviors (OOP). - Use
constwith function parameters when you donβt intend to modify.
Pitfalls:
- Forgetting to initialize members
- Confusing structure copying (by value) with reference
Diagram β Structure Memory Layout
+-------------------+
| id (int) |
+-------------------+
| name (string) |
+-------------------+
| salary (float) |
+-------------------+
| Total = size sum |
+-------------------+
The size of a structure depends on padding and alignment (platform/compiler dependent).
Comparison β Struct vs Class in C++
| Feature | struct | class |
|---|---|---|
| Default Access Spec. | public | private |
| Supports Functions | Yes | Yes |
| Inheritance Support | Yes | Yes |
| Use Case | Lightweight groups | Full OOP (Abstraction) |
| Memory/Performance | Same (no difference) | Same (depends on use) |
Real-World Use Cases
Use Cases:
- Representing student or employee records
- Game development (coordinates, objects, player stats)
- File format headers
- APIs and data exchange structures
Summary β Recap & Next Steps
C++ structures offer a powerful way to group related data, with support for OOP features like functions, constructors, and encapsulation.
Key Takeaways:
- Use
structfor logical grouping of variables - Can include member functions, constructors, and even inheritance
- Great for clean, organized code and data models
Next Steps:
- Learn about C++ Classes and Objects
- Explore C++ Inheritance & Polymorphism from structures
FAQ Section
What is the default access modifier in a C++ struct?
public β unlike class, which defaults to private.
Can a structure have a constructor in C++?
Yes, unlike C, C++ structures can have constructors, destructors, and member functions.
Are C++ structs and classes the same?
Almost β except that struct members are public by default, and class members are private by default.
Can a struct inherit from another struct/class?
Yes. C++ allows inheritance for structs, just like classes.
How is memory allocated in a structure?
Memory is sequentially allocated for each member with padding (depends on compiler).
Share Now :
