Structures & Unions
Structures and unions are powerful features in C++ that allow you to create custom data types by grouping related data together. While arrays store multiple values of the same type, structures enable you to combine different data types into a single entity, making it easier to model real-world objects and organize complex data. Understanding structures is essential before moving to classes, as structures form the foundation of object-oriented programming in C++.
1. Understanding Structures
A structure is a user-defined data type that groups related data items of different types under a single name. Structures allow you to create complex data types that represent real-world entities. For example, a Student structure can contain roll number (int), name (string), and marks (float) - all related to a single student entity.
Structures are particularly useful when you need to pass multiple related values to functions, return multiple values from functions, or organize data in a logical way. They provide better code organization and readability compared to using separate variables for each piece of related data.
Basic Structure
#include <iostream>
#include <string>
using namespace std;
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
Student s1;
s1.rollNo = 101;
s1.name = "John";
s1.marks = 85.5;
cout << "Roll No: " << s1.rollNo << endl;
cout << "Name: " << s1.name << endl;
cout << "Marks: " << s1.marks << endl;
return 0;
}Initialization
#include <iostream>
#include <string>
using namespace std;
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
// Initialization at declaration
Student s1 = {101, "John", 85.5};
// Designated initialization (C++20)
Student s2 = {.rollNo = 102, .name = "Alice", .marks = 90.0};
return 0;
}2. Structure with Functions
#include <iostream>
#include <string>
using namespace std;
struct Rectangle {
int length;
int width;
// Member function
int area() {
return length * width;
}
void setDimensions(int l, int w) {
length = l;
width = w;
}
};
int main() {
Rectangle r;
r.setDimensions(5, 3);
cout << "Area: " << r.area() << endl;
return 0;
}3. Array of Structures
#include <iostream>
#include <string>
using namespace std;
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
Student students[3];
// Input
for (int i = 0; i < 3; i++) {
cout << "Enter roll no, name, marks: ";
cin >> students[i].rollNo;
cin >> students[i].name;
cin >> students[i].marks;
}
// Display
for (int i = 0; i < 3; i++) {
cout << students[i].rollNo << " "
<< students[i].name << " "
<< students[i].marks << endl;
}
return 0;
}4. Nested Structures
#include <iostream>
#include <string>
using namespace std;
struct Date {
int day;
int month;
int year;
};
struct Employee {
int id;
string name;
Date birthDate; // Nested structure
float salary;
};
int main() {
Employee emp;
emp.id = 101;
emp.name = "John";
emp.birthDate.day = 15;
emp.birthDate.month = 5;
emp.birthDate.year = 1990;
emp.salary = 50000;
cout << "Employee: " << emp.name << endl;
cout << "DOB: " << emp.birthDate.day << "/"
<< emp.birthDate.month << "/"
<< emp.birthDate.year << endl;
return 0;
}5. Structure Pointers
#include <iostream>
#include <string>
using namespace std;
struct Student {
int rollNo;
string name;
float marks;
};
int main() {
Student s = {101, "John", 85.5};
Student *ptr = &s;
// Accessing using pointer
cout << (*ptr).rollNo << endl;
cout << ptr->name << endl; // Arrow operator
cout << ptr->marks << endl;
// Dynamic allocation
Student *s2 = new Student;
s2->rollNo = 102;
s2->name = "Alice";
s2->marks = 90.0;
delete s2;
return 0;
}6. typedef with Structures
#include <iostream>
#include <string>
using namespace std;
struct Student {
int rollNo;
string name;
float marks;
};
typedef Student Stu; // Create alias
int main() {
Stu s1; // Same as Student s1;
s1.rollNo = 101;
s1.name = "John";
s1.marks = 85.5;
return 0;
}7. Unions
A union is similar to a structure, but all members share the same memory location. Only one member can be accessed at a time:
#include <iostream>
using namespace std;
union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
Data d;
d.intValue = 10;
cout << "Integer: " << d.intValue << endl;
d.floatValue = 3.14;
cout << "Float: " << d.floatValue << endl;
// intValue is now overwritten
d.charValue = 'A';
cout << "Char: " << d.charValue << endl;
// Both intValue and floatValue are overwritten
return 0;
}8. Structure vs Union
| Feature | Structure | Union |
|---|---|---|
| Memory | Each member has separate memory | All members share same memory |
| Size | Sum of all members (with padding) | Size of largest member |
| Access | All members can be accessed | Only one member at a time |
| Use Case | Group related data | Save memory, type conversion |
Summary
| Topic | Key Points | Difficulty |
|---|---|---|
| Structures | User-defined type grouping different data types, each member has separate memory | Beginner |
| Structure Initialization | Can initialize at declaration, use designated initializers (C++20) | Beginner |
| Nested Structures | Structure within structure, access using dot operator chain | Intermediate |
| Structure Pointers | Use -> operator or (*ptr).member to access members via pointer | Intermediate |
| Unions | All members share same memory, size = largest member, only one active at a time | Intermediate |
| Structure vs Union | Structures: separate memory, unions: shared memory for memory efficiency | Intermediate |
Frequently Asked Questions
Q1: What is the difference between a structure and a class in C++?
In C++, structures and classes are almost identical. The only difference is default access: structure members are public by default, while class members are private by default. Structures can have member functions, constructors, destructors, and all class features. Use structures for simple data grouping, classes for full OOP with encapsulation.
Q2: When should I use a union instead of a structure?
Use unions when you need to save memory and only one member will be active at a time. Common uses: type conversion, implementing variant types, embedded systems with limited memory, network protocols with different message formats. Structures are preferred when you need all members simultaneously.
Q3: How do I pass a structure to a function?
You can pass structures by value (copies the entire structure), by reference (no copy, can modify original), or by pointer (efficient, can modify original). For large structures, prefer pass by reference or pointer to avoid copying overhead. Example: void func(Student &s) or void func(Student *s).
Q4: Can structures have member functions in C++?
Yes, C++ structures can have member functions, constructors, destructors, and all features that classes have. This is a major difference from C structures. In C++, structures are essentially classes with public default access. You can define methods inside structures just like in classes.
Q5: What is structure padding and why does it happen?
Structure padding is when the compiler adds extra bytes between members to align data on memory boundaries for efficient access. For example, a structure with char (1 byte) and int (4 bytes) might be 8 bytes total due to padding. This improves performance but can waste memory. Use #pragma pack to control padding, but be careful with portability.
Q6: How do I initialize a structure array?
You can initialize structure arrays using nested braces: Student arr[] = {{101, "John", 85.5}, {102, "Alice", 90.0}}. Each inner brace initializes one structure element. You can also initialize element by element using loops or individual assignment statements after declaration.
Q7: What happens if I access the wrong member in a union?
Accessing a union member that wasn't the last one written to results in undefined behavior. The memory contains the bit pattern from the last written member, which may not represent a valid value for the type you're reading. Always track which union member is currently active, or use tagged unions (union with an enum indicating active member).
Q8: Can I return a structure from a function?
Yes, you can return structures by value from functions. Modern compilers optimize this using return value optimization (RVO) or move semantics, avoiding unnecessary copies. For large structures, consider returning by reference or pointer, but be careful about object lifetime. Returning by value is safe and often efficient due to compiler optimizations.
Conclusion
Structures and unions are essential tools in C++ for organizing and managing related data. Structures allow you to group different data types together, creating meaningful abstractions that model real-world entities. Unions provide memory-efficient alternatives when only one member needs to be active at a time.
Understanding when to use structures versus unions, how to work with nested structures, and how to efficiently pass structures to functions are important skills. Structures form the foundation for classes in C++, and many concepts you learn with structures directly apply to object-oriented programming.
As you progress in C++, you'll find that structures are used extensively in system programming, data structures, and when interfacing with C code. Mastery of structures and unions enables you to write more organized, maintainable, and efficient C++ programs.
Related Links
🔹 Author: Dr. J. Siva Ramakrishna
🔹 Institution: Narayana Engineering College, Gudur
🔹 Last Updated: 9 January 2026