C++ Structures

🧩 C++ Structures (struct)

A structure (struct) in C++ is a user-defined data type that allows you to group different data types under a single name.
It is very useful for representing real-world entities like students, employees, products, etc.


 1. Why Use struct?

An array can store only one data type, but a structure can store:

  • int

  • float

  • string

  • char

  • etc.
    all together in one unit


 2. Defining a Structure

struct Student {
int id;
string name;
float marks;
};

👉 This only defines the structure (no memory allocated yet).


 3. Creating Structure Variables (Objects)

Student s1;

 4. Accessing Structure Members (. operator)

s1.id = 101;
s1.name = "Rahul";
s1.marks = 85.5;
cout << s1.name;

 5. Structure Initialization

Student s2 = {102, "Amit", 90.0};

 6. Complete Example Program

#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
float marks;
};int main() {
Student s1 = {101, “Sanjit”, 88.5};

cout << “ID: “ << s1.id << endl;
cout << “Name: “ << s1.name << endl;
cout << “Marks: “ << s1.marks << endl;

return 0;
}


 7. Array of Structures

Student students[2];

students[0] = {101, “Rahul”, 85};
students[1] = {102, “Anita”, 92};

for (int i = 0; i < 2; i++) {
cout << students[i].name << endl;
}


8. Structure with User Input

Student s;

cin >> s.id;
cin.ignore();
getline(cin, s.name);
cin >> s.marks;


9. Nested Structures

struct Address {
string city;
int pin;
};
struct Person {
string name;
Address addr;
};

 10. struct vs class

struct class
Members are public by default Members are private by default
Used for data grouping Used for OOP
Simple More control

📌 Summary

  • struct groups different data types

  • Members accessed using . operator

  • Useful for real-world data modeling

  • Arrays of structures are very powerful

You may also like...