๐Ÿ“ฆ C++ Arrays & Structures
Estimated reading: 4 minutes 30 views

๐Ÿงฑ 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 and class 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 name
  • s1 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 or using for long struct names.
  • Initialize members properly using constructors (if added).
  • Keep functions inside structures short and focused.

๐Ÿ’ก Tips:

  • Prefer class over struct 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++

Featurestructclass
Default Access Spec.publicprivate
Supports Functionsโœ… Yesโœ… Yes
Inheritance Supportโœ… Yesโœ… Yes
Use CaseLightweight groupsFull OOP (Abstraction)
Memory/PerformanceSame (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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

C++ Structures

Or Copy Link

CONTENTS
Scroll to Top