๐งฑ 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
struct
andclass
in 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:
Student
is the structure names1
is 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
typedef
orusing
for long struct names. - Initialize members properly using constructors (if added).
- Keep functions inside structures short and focused.
๐ก Tips:
- Prefer
class
overstruct
when implementing complex behaviors (OOP). - Use
const
with 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
struct
for 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 :