Lesson 44 of 60 – Structures in C++
73%

Structures in C++

A structure in C++ is a user-defined data type that allows us to group related variables of different data types under one name. Structures are useful for representing real-world objects such as students, employees, products, books, and customers.

Note: A structure can contain members of different data types, and objects of the structure can be created to store actual data.

1. What is a Structure?

A structure is a user-defined data type that groups related data together.

For example, a student may have:

  • Name
  • Age
  • Marks
  • Grade

These values can be grouped inside one structure.

2. Structure Syntax

The basic syntax of a structure is:

struct StructureName {

    dataType member1;
    dataType member2;
    dataType member3;

};

The semicolon after the closing brace is required.

3. Creating a Simple Structure

struct Student {

    std::string name;
    int age;
    float marks;

};

Here, Student is a structure containing three members: name, age, and marks.

4. Creating a Structure Object

After defining a structure, we can create objects of that structure.

struct Student {

    std::string name;
    int age;
    float marks;

};

int main() {

    Student student1;

    return 0;
}

Here, student1 is an object of the Student structure.

5. Assigning Values to Structure Members

Student student1;

student1.name = "Rahul";
student1.age = 20;
student1.marks = 85.5;

The dot operator . is used to access structure members.

6. Accessing Structure Members

std::cout << student1.name << std::endl;
std::cout << student1.age << std::endl;
std::cout << student1.marks;

The dot operator connects the structure object with the required member.

7. Complete Structure Example

#include <iostream>
#include <string>

struct Student {

    std::string name;
    int age;
    float marks;

};

int main() {

    Student student1;

    student1.name = "Amit";
    student1.age = 21;
    student1.marks = 88.5;

    std::cout << student1.name
              << std::endl;

    std::cout << student1.age
              << std::endl;

    std::cout << student1.marks;

    return 0;
}

8. Structure with Different Data Types

A structure can contain different data types.

struct Employee {

    std::string name;
    int age;
    double salary;
    char grade;
    bool permanent;

};

One structure can therefore group several kinds of related data.

9. Initializing a Structure Object

Structure objects can be initialized using braces.

struct Student {

    std::string name;
    int age;
    float marks;

};

Student student1 = {
    "Ravi",
    20,
    91.5
};

The values are assigned in the same order as the members.

10. Multiple Structure Objects

Student student1;
Student student2;
Student student3;

student1.name = "Amit";
student2.name = "Ravi";
student3.name = "Neha";

Many objects can be created from the same structure definition.

11. Structure Object Example

#include <iostream>
#include <string>

struct Product {

    std::string name;
    double price;
    int quantity;

};

int main() {

    Product product1;

    product1.name = "Laptop";
    product1.price = 55000;
    product1.quantity = 2;

    std::cout << "Product: "
              << product1.name
              << std::endl;

    std::cout << "Price: "
              << product1.price
              << std::endl;

    std::cout << "Quantity: "
              << product1.quantity;

    return 0;
}

12. Structure and Functions

A structure object can be passed to a function.

void displayStudent(Student student) {

    std::cout << student.name;
}

The function receives a structure object as its parameter.

13. Passing Structure by Reference

A structure can be passed by reference when the function needs to modify the original object.

void updateMarks(Student& student) {

    student.marks = 95;
}

Because the parameter is a reference, changes affect the original object.

14. Passing Structure Using const Reference

A structure can be passed using a const reference when a function needs to read the object without modifying it.

void displayStudent(
    const Student& student
) {

    std::cout << student.name;
}

This avoids making a copy while preventing modification through the parameter.

15. Returning a Structure from a Function

A function can return a structure object.

Student createStudent() {

    Student student;

    student.name = "Rahul";
    student.age = 20;
    student.marks = 85;

    return student;
}

The returned structure can be stored in another structure object.

16. Structure Inside Another Structure

A structure can contain another structure as a member.

struct Address {

    std::string city;
    std::string state;

};

struct Student {

    std::string name;
    Address address;

};

Here, Student contains an Address object.

17. Accessing Nested Structure Members

Student student1;

student1.name = "Amit";

student1.address.city = "Patna";

student1.address.state = "Bihar";

std::cout << student1.address.city;

The dot operator can be used multiple times to access nested members.

18. Array of Structures

An array can contain multiple objects of the same structure.

Student students[3];

The array can store three Student objects.

students[0].name = "Amit";
students[1].name = "Ravi";
students[2].name = "Neha";

19. Loop Through an Array of Structures

Student students[3] = {

    {"Amit", 20, 85},
    {"Ravi", 21, 90},
    {"Neha", 19, 92}

};

for (int i = 0; i < 3; i++) {

    std::cout << students[i].name
              << " "
              << students[i].marks
              << std::endl;
}

This is useful for storing and processing records.

20. Structure with a Constructor

In C++, a structure can have member functions and constructors just like a class.

struct Student {

    std::string name;
    int age;

    Student(
        std::string n,
        int a
    ) {

        name = n;
        age = a;
    }
};

Student student1("Amit", 20);

The constructor initializes the structure object.

21. Structure with a Member Function

struct Student {

    std::string name;
    int marks;

    void display() {

        std::cout << name
                  << " "
                  << marks;
    }
};

A structure in C++ can contain functions as well as data members.

22. Structure Pointer

A pointer can point to a structure object.

Student student;

Student* ptr = &student;

When using a pointer to access structure members, the -> operator is commonly used.

ptr->name = "Rahul";
ptr->marks = 90;

23. Dot Operator vs Arrow Operator

Operator Used With Example
. Structure object student.name
-> Pointer to structure ptr->name

24. Structure vs Class

In C++, structures and classes are very similar. Both can contain data members, member functions, constructors, and other features.

Structure Class
Default member access is public. Default member access is private.
Often convenient for simple data grouping. Often used when stronger encapsulation is desired.
Can contain functions and constructors. Can contain functions and constructors.

25. Practical Employee Structure

#include <iostream>
#include <string>

struct Employee {

    int id;
    std::string name;
    double salary;

};

int main() {

    Employee employee;

    employee.id = 101;
    employee.name = "Rahul";
    employee.salary = 35000;

    std::cout << "ID: "
              << employee.id
              << std::endl;

    std::cout << "Name: "
              << employee.name
              << std::endl;

    std::cout << "Salary: "
              << employee.salary;

    return 0;
}

26. Practical Student Result Program

#include <iostream>
#include <string>

struct Student {

    std::string name;
    int marks;

};

int main() {

    Student student;

    student.name = "Amit";
    student.marks = 78;

    std::cout << "Student: "
              << student.name
              << std::endl;

    std::cout << "Marks: "
              << student.marks
              << std::endl;

    if (student.marks >= 40) {

        std::cout << "Result: Pass";

    } else {

        std::cout << "Result: Fail";
    }

    return 0;
}

27. Common Structure Mistakes

  • Forgetting the semicolon after the structure definition.
  • Trying to access a member without an object or pointer.
  • Using -> with a normal structure object.
  • Using . incorrectly with a structure pointer.
  • Providing structure initialization values in the wrong order.
  • Confusing a structure object with the structure definition.
  • Forgetting to include required headers such as <string>.

28. Best Practices for Structures

  • Use meaningful structure names.
  • Use meaningful member names.
  • Group closely related data in one structure.
  • Use const references when passing large structures for read-only access.
  • Use references when a function needs to modify the original structure.
  • Use arrays or containers when multiple records are required.
  • Keep structure responsibilities clear and simple.

29. Real-World Uses of Structures

Structures are useful in many programming applications.

  • Student Management: name, ID, class, marks.
  • Employee Management: employee ID, name, salary.
  • Library Systems: book ID, title, author, price.
  • Banking Systems: account number, name, balance.
  • Product Systems: product name, price, quantity.
  • Address Records: city, state, country, PIN code.

30. Structures – Final Summary

Concept Meaning
Structure A user-defined data type for grouping related data.
Member A variable or function defined inside a structure.
Object An instance of a structure.
Dot Operator Used to access members through an object.
Array of Structures Stores multiple objects of the same structure.
Structure Pointer Stores the address of a structure object.
Arrow Operator Used to access members through a structure pointer.
struct Student {

    std::string name;
    int age;
    float marks;

};

int main() {

    Student student;

    student.name = "Amit";
    student.age = 20;
    student.marks = 88.5;

    std::cout << student.name;

    return 0;
}

📌 Key Points

  • A structure is a user-defined data type.
  • Structures group related variables under one name.
  • A structure can contain different data types.
  • Structure objects are created from the structure definition.
  • The dot operator is used to access members through an object.
  • Structures can be passed to and returned from functions.
  • Structures can contain arrays, other structures, functions, and constructors.
  • An array of structures can store multiple records.
  • The arrow operator is used with a pointer to a structure.
  • C++ structures can support many features also available to classes.

🧠 Quick Quiz

Question: Which operator is normally used to access a member of a structure object in C++?