πŸ“¦ C++ Arrays & Structures
Estimated reading: 4 minutes 341 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 :
Share

C++ Structures

Or Copy Link

CONTENTS
Scroll to Top