Topic 37 of 91 7. C++ Structures and Unions Interactive Tutorial

Structures in C++: Building Custom Data Records With struct

15 mins read Last updated: 26 Sep 2026 21,600 views

Direct Answer & Core Concept

In C++, variables are used to store individual values such as integers, floating-point numbers, characters, and strings. However, real-world applications often need to store several related values together.

For example, a student record may contain:

  • Student ID

  • Student name

  • Age

  • Marks

  • Grade

Creating separate variables for every student can make a program difficult to manage. C++ provides a feature called structures (struct) that allows you to group related variables of different data types under one name.

Detailed Explanation & Mechanics

1. What Is a Structure in C++?

A structure is a user-defined data type that groups multiple related data members under a single name.

Each member can have a different data type.

For example, a student structure can store an ID, name, age, and marks.

Syntax of a Structure

main.cpp
Run Online
struct StructureName {
    data_type member1;
    data_type member2;
    data_type member3;
};

Here:

  • struct is the keyword used to declare a structure.

  • StructureName is the name of the structure.

  • member1, member2, and member3 are its data members.

  • The semicolon after the closing brace is required.

Example: Create a Student Structure

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

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

int main() {
    return 0;
}

In this example, Student is a user-defined type containing four members:

MemberData typePurpose
idintStores student ID
namestringStores student name
ageintStores student age
marksfloatStores student marks

Declaring a structure defines a type. It does not automatically create a student record object.

2. Declaring Structure Variables

After defining a structure, you can create variables of that structure type.

Syntax

main.cpp
Run Online
StructureName variableName;

Example:

main.cpp
Run Online
Student student1;
Student student2;

Both variables contain their own copies of the structure members.

You can also declare multiple variables of the same structure type:

main.cpp
Run Online
Student student1, student2, student3;

Example: Declare and Display a Structure Variable

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id;
    string name;
    int age;
};

int main() {
    Student student1;

    student1.id = 101;
    student1.name = "Rahul";
    student1.age = 20;

    cout << "Student ID: " << student1.id << endl;
    cout << "Name: " << student1.name << endl;
    cout << "Age: " << student1.age << endl;

    return 0;
}

Output:

main.cpp
Run Online
Student ID: 101
Name: Rahul
Age: 20

The program creates a structure variable named student1 and assigns values to its members.

3. Accessing Structure Members Using the Dot Operator

The dot (.) operator is used to access individual members of a structure variable.

Syntax

Example:

main.cpp
Run Online
student1.id = 101;
student1.name = "Rahul";
student1.age = 20;

You can also read and display individual members:

main.cpp
Run Online
cout << student1.id;
cout << student1.name;

The dot operator is used when you have a structure object or reference.

4. Initializing a Structure in C++

You can assign values to structure members when creating a structure variable.

Example 1: Aggregate Initialization

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id;
    string name;
    int age;
};

int main() {
    Student student1 = {101, "Rahul", 20};

    cout << student1.id << endl;
    cout << student1.name << endl;
    cout << student1.age << endl;

    return 0;
}

Output:

The values are assigned in the order in which the members are declared.

Example 2: Initialize With Default Member Values

You can provide default values directly in the structure definition.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id = 0;
    string name = "Unknown";
    int age = 18;
};

int main() {
    Student student1;

    cout << student1.id << endl;
    cout << student1.name << endl;
    cout << student1.age << endl;

    return 0;
}

Output:

Default member initializers are used when a member is not otherwise initialized.

Example 3: Initialize Selected Members Using Designated Initializers

C++20 supports designated initializers for aggregates.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id;
    string name;
    int age;
};

int main() {
    Student student1 = {
        .id = 101,
        .name = "Rahul",
        .age = 20
    };

    cout << student1.name;

    return 0;
}

Output:

In C++, designated initializers must follow the declaration order of the members.

5. Taking User Input in a Structure

You can use cin and getline() to receive values for structure members.

Example: Enter Student Details

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

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

int main() {
    Student student1;

    cout << "Enter student ID: ";
    cin >> student1.id;

    cout << "Enter student name: ";
    cin >> student1.name;

    cout << "Enter age: ";
    cin >> student1.age;

    cout << "Enter marks: ";
    cin >> student1.marks;

    cout << "\nStudent Details" << endl;
    cout << "ID: " << student1.id << endl;
    cout << "Name: " << student1.name << endl;
    cout << "Age: " << student1.age << endl;
    cout << "Marks: " << student1.marks << endl;

    return 0;
}

Sample input:

Output:

main.cpp
Run Online
Student Details
ID: 101
Name: Rahul
Age: 20
Marks: 85.5

If you want to accept a full name containing spaces, use getline() instead of cin >> for the name.

For example:

main.cpp
Run Online
cout << "Enter student name: ";
getline(cin >> ws, student1.name);

The std::ws manipulator consumes leading whitespace, including a leftover newline, before reading the name.

6. Modifying Structure Members

Structure members can be modified after the object has been created.

Example

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Employee {
    int id;
    string name;
    double salary;
};

int main() {
    Employee emp = {101, "Amit", 30000};

    cout << "Old Salary: " << emp.salary << endl;

    emp.salary = 45000;

    cout << "Updated Salary: " << emp.salary << endl;

    return 0;
}

Output:

main.cpp
Run Online
Old Salary: 30000
Updated Salary: 45000

The assignment changes the salary member of the emp object.

7. Array of Structures in C++

An array of structures allows you to store multiple records of the same type.

For example, an employee management system may need to store information about many employees.

Syntax

main.cpp
Run Online
StructureName arrayName[size];

Example: Store Multiple Student Records

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

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

int main() {
    Student students[3] = {
        {101, "Rahul", 85.5},
        {102, "Amit", 90.0},
        {103, "Priya", 92.5}
    };

    for (int i = 0; i < 3; i++) {
        cout << "Student " << i + 1 << endl;
        cout << "ID: " << students[i].id << endl;
        cout << "Name: " << students[i].name << endl;
        cout << "Marks: " << students[i].marks << endl;
        cout << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
Student 1
ID: 101
Name: Rahul
Marks: 85.5

Student 2
ID: 102
Name: Amit
Marks: 90

Student 3
ID: 103
Name: Priya
Marks: 92.5

Explanation:

  • Student students[3] creates an array containing three student records.

  • students[0] accesses the first student.

  • students[1] accesses the second student.

  • students[i].name accesses the name of the selected student.

Arrays of structures are useful in student, employee, inventory, and customer management systems.

8. Nested Structures in C++

A nested structure is a structure declared as a member of another structure.

This is useful when a record contains another group of related information.

For example, an employee may have personal information and address information.

Example: Employee With Address Details

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Address {
    string city;
    string state;
    int pinCode;
};

struct Employee {
    int id;
    string name;
    Address address;
};

int main() {
    Employee emp = {
        101,
        "Amit",
        {"Kolkata", "West Bengal", 700001}
    };

    cout << "Employee ID: " << emp.id << endl;
    cout << "Name: " << emp.name << endl;
    cout << "City: " << emp.address.city << endl;
    cout << "State: " << emp.address.state << endl;
    cout << "PIN Code: " << emp.address.pinCode << endl;

    return 0;
}

Output:

main.cpp
Run Online
Employee ID: 101
Name: Amit
City: Kolkata
State: West Bengal
PIN Code: 700001

Here, Employee contains an Address structure as one of its members.

You can access nested members using multiple dot operators:

9. Passing a Structure to a Function

You can pass a structure object to a function in C++ just like other variables.

There are three common techniques:

  1. Pass by value.

  2. Pass by reference.

  3. Pass by constant reference.

9.1 Pass a Structure by Value

When a structure is passed by value, the function receives a copy of the object.

Changes made to that copy do not modify the original object.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id;
    string name;
};

void display(Student s) {
    cout << "ID: " << s.id << endl;
    cout << "Name: " << s.name << endl;
}

int main() {
    Student student1 = {101, "Rahul"};

    display(student1);

    return 0;
}

Output:

9.2 Pass a Structure by Reference

Passing by reference allows a function to modify the original structure object.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Employee {
    int id;
    string name;
    double salary;
};

void updateSalary(Employee& emp) {
    emp.salary = 50000;
}

int main() {
    Employee emp = {101, "Amit", 30000};

    updateSalary(emp);

    cout << "Updated Salary: " << emp.salary;

    return 0;
}

Output:

The Employee& parameter refers to the original object.

9.3 Pass a Structure by Constant Reference

If a function only needs to read a structure, use a constant reference.

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id;
    string name;
};

void display(const Student& s) {
    cout << s.id << endl;
    cout << s.name << endl;
}

int main() {
    Student student1 = {101, "Rahul"};

    display(student1);

    return 0;
}

Output:

This avoids copying the structure and prevents modification through the function parameter.

10. Returning a Structure From a Function

A C++ function can return a structure object by value.

This is useful when a function needs to create and return a complete record.

Example: Return Employee Details

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Employee {
    int id;
    string name;
    double salary;
};

Employee createEmployee() {
    Employee emp = {101, "Amit", 45000};

    return emp;
}

int main() {
    Employee emp = createEmployee();

    cout << "ID: " << emp.id << endl;
    cout << "Name: " << emp.name << endl;
    cout << "Salary: " << emp.salary << endl;

    return 0;
}

Output:

main.cpp
Run Online
ID: 101
Name: Amit
Salary: 45000

Returning structures by value is a normal and safe C++ technique. Modern compilers can often eliminate unnecessary copies.

11. Pointers to Structures in C++

A pointer can store the address of a structure object.

When accessing structure members through a pointer, you can use the arrow (->) operator.

Syntax

This is equivalent to:

main.cpp
Run Online
(*pointerName).memberName;

Example: Access Structure Members Using a Pointer

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Employee {
    int id;
    string name;
    double salary;
};

int main() {
    Employee emp = {101, "Amit", 45000};

    Employee* ptr = &emp;

    cout << "ID: " << ptr->id << endl;
    cout << "Name: " << ptr->name << endl;
    cout << "Salary: " << ptr->salary << endl;

    return 0;
}

Output:

main.cpp
Run Online
ID: 101
Name: Amit
Salary: 45000

The pointer ptr stores the address of emp. The arrow operator accesses its members.

12. Structure With Functions as Members

In C++, a structure can contain member functions in addition to data members.

This allows you to group related data and operations together.

Example: Structure With a Member Function

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

struct Student {
    int id;
    string name;

    void display() {
        cout << "ID: " << id << endl;
        cout << "Name: " << name << endl;
    }
};

int main() {
    Student student1 = {101, "Rahul"};

    student1.display();

    return 0;
}

Output:

The display() function belongs to the Student structure and can access its members directly.

Structures can also contain constructors, operators, and other member functions.

13. Difference Between struct and class in C++

Both struct and class are used to define user-defined types in C++.

They support:

  • Data members.

  • Member functions.

  • Constructors and destructors.

  • Inheritance.

  • Access control.

  • Operator overloading.

The main language-level differences are their default access and inheritance rules.

Featurestructclass
Default member accessPublicPrivate
Default inheritance accessPublicPrivate
Member functionsSupportedSupported
ConstructorsSupportedSupported
InheritanceSupportedSupported
Operator overloadingSupportedSupported
Common conventionSimple data recordsEncapsulated objects

Example: struct

main.cpp
Run Online
struct Student {
    int id;  // Public by default
};

You can access the member directly:

Example: class

main.cpp
Run Online
class Student {
    int id;  // Private by default

public:
    void setId(int value) {
        id = value;
    }
};

The private member cannot be accessed directly from outside the class. The public function provides controlled access.

Important: A C++ struct is not limited to storing data. It can provide the same general capabilities as a class.

14. Real-World Applications of Structures in C++

Structures are useful when a program needs to manage related information as a single record.

Common applications include:

Student Management Systems

Store student IDs, names, marks, grades, and other academic details.

Employee Management Systems

Store employee names, IDs, salaries, department information, and contact details.

Banking Applications

Represent account numbers, customer names, and account balances.

Inventory Management

Store product IDs, product names, prices, and stock quantities.

Library Management Systems

Represent books with titles, authors, ISBN numbers, and availability information.

Game Development

Represent positions, player statistics, coordinates, and game-related records.

15. Common Mistakes When Using Structures

Mistake 1: Forgetting the Semicolon

Incorrect:

main.cpp
Run Online
struct Student {
    int id;
    string name;
}

Correct:

main.cpp
Run Online
struct Student {
    int id;
    string name;
};

A structure definition must end with a semicolon.

Mistake 2: Accessing Members Without an Object

Incorrect:

Correct:

main.cpp
Run Online
Student student1;
student1.id = 101;

You need a structure object to access its non-static data members.

Mistake 3: Using the Wrong Member Operator

Use the dot operator for an object:

Use the arrow operator for a pointer:

Mistake 4: Forgetting to Initialize Members

Local structure variables without an initializer may contain members with indeterminate values when those members are not initialized by default member initializers or constructors.

Initialize the object when appropriate:

Value initialization initializes the members using their applicable initialization rules.

Mistake 5: Confusing struct With an Array

A structure groups different members into one record.

An array stores multiple elements of the same type.

For example:

main.cpp
Run Online
struct Student {
    int id;
    string name;
};

This defines one student record type.

This creates an array of ten student records.

16. Best Practices for Using Structures

  1. Use meaningful structure names such as Student, Employee, and Product.

  2. Group only logically related information together.

  3. Initialize structure objects before using their members.

  4. Use const references when passing large structures that do not need modification.

  5. Use ordinary references when a function must update the original object.

  6. Use arrays or standard containers when managing multiple records.

  7. Prefer std::string for text rather than manually managed character arrays.

  8. Use private members and public functions when you need controlled access to data.

  9. Keep structure definitions organized and reusable.

  10. Consider a class when the type needs stronger encapsulation or complex behavior.

17. Frequently Asked Questions (FAQs)

1. What is a structure in C++?

A structure is a user-defined data type that groups related variables, possibly of different data types, under one name.

2. Which keyword is used to create a structure?

The struct keyword is used to define a structure in C++.

3. How do you declare a structure variable?

Use the structure type name followed by the variable name:

4. How do you access structure members?

Use the dot (.) operator:

5. Can a structure contain different data types?

Yes. A structure can contain members such as int, float, double, char, std::string, arrays, and other structure types.

6. Can we create an array of structures?

Yes. You can create an array of structure objects:

7. Can a structure contain another structure?

Yes. This is called a nested structure. One structure can be declared as a member of another structure.

8. Can a structure be passed to a function?

Yes. A structure can be passed by value, by reference, or by constant reference.

9. Can a function return a structure?

Yes. A C++ function can return a structure object by value.

10. What is the difference between dot and arrow operators?

The dot operator (.) accesses a member through an object. The arrow operator (->) accesses a member through a pointer to an object.

11. Can a structure contain functions?

Yes. C++ structures can contain member functions, constructors, and other class-like features.

12. What is the difference between struct and class?

The main difference is default access: members of a struct are public by default, while members of a class are private by default. Their default inheritance access also differs.

Runnable Code Example: Structures in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <string>

// Plain Old Data (POD) / Aggregate struct
struct DatabaseRecord {
    int recordId;
    std::string tableName;
    double queryLatencyMs;

    void display() const {
        std::cout << "[Record #" << recordId << "] Table: " << tableName 
                  << " | Latency: " << queryLatencyMs << " ms
";
    }
};

int main() {
    // Designated initializers (C++20)
    DatabaseRecord record{1001, "users_auth", 1.42};
    record.display();

    std::cout << "DatabaseRecord Size: " << sizeof(record) << " bytes
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is struct memory padding and alignment in C++?

A: CPU hardware reads memory efficiently in aligned chunks (e.g. 4 or 8 bytes). If a 1-byte char is followed by an 8-byte double, the compiler inserts 7 padding bytes to ensure the double starts at a multiple of 8.
Q

Q: What is an aggregate struct in C++?

A: An aggregate is a class/struct with no user-declared constructors, no private/protected non-static data members, and no virtual functions, allowing direct brace initialization `StructName{a, b, c}`.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use struct for passive Plain Old Data (POD) / Data Transfer Objects (DTOs).
2. Use class when enforcing invariants, private encapsulation, and complex behavior.
3. Order struct data members from largest to smallest to minimize memory padding waste.