Structures in C++
Why Use Structures?
Structures in C++ allow grouping related data of different types under one name. They are
essential for:
1. Organizing complex data efficiently.
2. Enhancing code readability and maintainability.
3. Providing a way to define custom data types for specific requirements.
4. Enabling data abstraction in larger programs.
For example, to manage data for a Student with attributes like name, age, and grade, you
can use a structure.
Structure Declaration
A structure is declared using the struct keyword.
Syntax:
struct StructureName {
DataType Member1;
DataType Member2;
// More members...
};
Example:
struct Student {
string name;
int age;
float grade; };
Declaring Structure Variables
Structure variables can be declared:
1. Directly after structure definition.
2. Using the structure type in the program.
Example:
struct Student {
string name;
int age;
float grade;
};
Student s1, s2; // Declaring structure variables
Initializing Structure Variables
You can initialize structure variables at the time of declaration or later.
Example:
struct Student {
string name;
int age;
float grade;
};
// Direct initialization
Student s1 = {"John Doe", 20, 3.8};
// Separate initialization
Student s2;
s2.name = "Jane Smith";
s2.age = 22;
s2.grade = 3.9;
Accessing Structure Elements
The dot (.) operator is used to access members of a structure.
Example:
cout << "Name: " << s1.name << endl;
cout << "Age: " << s1.age << endl;
cout << "Grade: " << s1.grade << endl;
Referencing Structure Members
You can use pointers to structures to reference structure members. The arrow (->)
operator is used when accessing members through pointers.
Example:
Student s3 = {"Alice", 19, 3.7};
Student *ptr = &s3;
cout << "Name: " << ptr->name << endl;
cout << "Age: " << ptr->age << endl;
cout << "Grade: " << ptr->grade << endl;
Code Implementation
Here’s a complete program to demonstrate all concepts:
#include <iostream>
#include <string>
using namespace std;
// Structure declaration
struct Student {
string name;
int age;
float grade;
};
int main() {
// Declaring structure variables
Student s1 = {"John Doe", 20, 3.8}; // Direct initialization
Student s2; // Declared but not initialized
// Initializing structure variables separately
s2.name = "Jane Smith";
s2.age = 22;
s2.grade = 3.9;
// Accessing structure members
cout << "Student 1:" << endl;
cout << "Name: " << s1.name << endl;
cout << "Age: " << s1.age << endl;
cout << "Grade: " << s1.grade << endl;
cout << "\nStudent 2:" << endl;
cout << "Name: " << s2.name << endl;
cout << "Age: " << s2.age << endl;
cout << "Grade: " << s2.grade << endl;
// Using a pointer to reference structure members
Student *ptr = &s1;
cout << "\nAccessing Student 1 using pointer:" << endl;
cout << "Name: " << ptr->name << endl;
cout << "Age: " << ptr->age << endl;
cout << "Grade: " << ptr->grade << endl;
return 0;
}
Output
Student 1:
Name: John Doe
Age: 20
Grade: 3.8
Student 2:
Name: Jane Smith
Age: 22
Grade: 3.9
Accessing Student 1 using pointer:
Name: John Doe
Age: 20
Grade: 3.8
Structures and Unions in C++
Nested Structures
Nested structures allow defining a structure within another structure.
This is useful for representing hierarchical data.
Example:
struct Address {
string city;
string state;
int zipCode;
};
struct Student {
string name;
int age;
Address address; // Nested structure
};
Accessing Nested Structures:
Student s1 = {"John Doe", 20, {"New York", "NY", 10001}};
cout << "Name: " << s1.name << endl;
cout << "City: " << s1.address.city << endl;
cout << "State: " << s1.address.state << endl;
cout << "Zip Code: " << s1.address.zipCode << endl;
Uses of Structures
Structures are widely used in programming for:
1. Grouping related data of different types.
2. Representing records in databases.
3. Passing multiple data items to functions as a single entity.
4. Creating complex data models like trees, graphs, and linked
lists.
Concept of Unions
A union is a special data type where all members share the same memory
location. At any point, only one member can hold a value, saving
memory.
Syntax:
union UnionName {
DataType Member1;
DataType Member2;
// More members...
};
Example:
union Data {
int intValue;
float floatValue;
char charValue;
};
Data d1;
d1.intValue = 10; // Setting intValue
cout << "Int Value: " << d1.intValue << endl;
d1.floatValue = 3.14; // Setting floatValue (overwrites intValue)
cout << "Float Value: " << d1.floatValue << endl;
Unions vs. Structures
Aspect Structure Union
Memor Allocates memory for all
All members share the same memory.
y Usage members separately.
Stores all member values
Storage Can store only one member value at a time.
simultaneously.
All members can be Changing one member affects others due to
Access
accessed independently. shared memory.
Use Used when all members Used for memory-efficient programs where only
Case need separate storage. one value is needed at a time.
Unions of Structures
Unions can also contain structures as members. This combines the
benefits of both constructs.
Example:
struct Student {
string name;
int age;
};
union Data {
Student student;
int id;
};
Data d;
d.id = 101; // Using id
cout << "ID: " << d.id << endl;
d.student = {"John Doe", 20}; // Using student (overwrites id)
cout << "Student Name: " << d.student.name << endl;
cout << "Age: " << d.student.age << endl;
Code Implementation: Structures and Unions
#include <iostream>
#include <string>
using namespace std;
struct Address {
string city;
string state;
int zipCode;
};
struct Student {
string name;
int age;
Address address; // Nested structure
};
union Data {
int id;
float salary;
char grade;
};
int main() {
// Nested Structure Example
Student s1 = {"Alice", 21, {"Los Angeles", "CA", 90001}};
cout << "Student Details:" << endl;
cout << "Name: " << s1.name << endl;
cout << "City: " << s1.address.city << endl;
cout << "State: " << s1.address.state << endl;
cout << "Zip Code: " << s1.address.zipCode << endl;
// Union Example
Data d;
d.id = 12345;
cout << "\nID: " << d.id << endl;
d.salary = 55000.75; // Overwrites id
cout << "Salary: " << d.salary << endl;
d.grade = 'A'; // Overwrites salary
cout << "Grade: " << d.grade << endl;
return 0;
}
Output
Student Details:
Name: Alice
City: Los Angeles
State: CA
Zip Code: 90001
ID: 12345
Salary: 55000.75
Grade: A
This illustrates the flexibility of structures and unions in managing
data, emphasizing their memory and organizational advantages.
C++ Structures with Methods, Variables
In C++, structures can have member functions (methods).
Structure Code Example
#include <iostream>
#include <string>
using namespace std;
struct Student {
private:
// Private members (not accessible outside the structure)
string studentID;
public:
// Public members (accessible outside the structure)
string name;
int age;
float grade;
// Public method to display student details
void displayDetails() {
cout << "Student ID: " << studentID << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;
}
// Public method to update student grade
void updateGrade(float newGrade) {
grade = newGrade;
}
// Getter for private studentID
string getStudentID() {
return studentID;
}
// Setter for private studentID
void setStudentID(string id) {
studentID = id;
}
};
int main() {
// Creating a Student object
Student s1("S123", "John Doe", 20, 3.8);
// Accessing public members
cout << "Initial Details:" << endl;
s1.displayDetails();
// Modifying grade using a method
s1.updateGrade(4.0);
cout << "\nUpdated Grade:" << endl;
s1.displayDetails();
// Using private member methods
s1.setStudentID("S456");
cout << "\nUpdated Student ID: " << s1.getStudentID() << endl;
return 0;
}
Key Features in the Code
1. Variables:
a. name, age, and grade are public and directly accessible.
b. studentID is private and accessed through getter and setter
methods.
2. Methods:
a. displayDetails(): Prints the structure's data.
b. updateGrade(): Updates the grade member.
c. getStudentID() and setStudentID(): Access and modify the
private studentID.
Output
Initial Details:
Student ID: S123
Name: John Doe
Age: 20
Grade: 3.8
Updated Grade:
Student ID: S123
Name: John Doe
Age: 20
Grade: 4
Updated Student ID: S456