Welcome to The Coding College! In this tutorial, we’ll explore structures (struct) in C++. A structure is a user-defined data type that allows grouping multiple variables of different types under a single name. This is especially useful for creating custom data models.
What Is a Structure in C++?
A structure is a way to define a custom data type that can hold multiple members, each of which can be of a different type. Structures are useful for organizing and managing complex data.
Syntax
struct StructureName {
data_type member1;
data_type member2;
// Additional members...
};
struct
: Keyword to define a structure.StructureName
: The name of the structure.member1
,member2
: Variables (members) that belong to the structure.
Defining and Using Structures
Example: Defining and Accessing a Structure
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
float height;
};
int main() {
// Create an instance of the structure
Person person1;
// Assign values to the members
person1.name = "John Doe";
person1.age = 25;
person1.height = 5.9;
// Access and display the values
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Height: " << person1.height << " ft" << endl;
return 0;
}
Output:
Name: John Doe
Age: 25
Height: 5.9 ft
Initializing Structures
You can initialize a structure directly during declaration.
Example: Initialization
#include <iostream>
using namespace std;
struct Car {
string brand;
string model;
int year;
};
int main() {
// Initialize structure
Car car1 = {"Tesla", "Model S", 2023};
// Display the values
cout << "Brand: " << car1.brand << endl;
cout << "Model: " << car1.model << endl;
cout << "Year: " << car1.year << endl;
return 0;
}
Output:
Brand: Tesla
Model: Model S
Year: 2023
Nested Structures
A structure can contain another structure as a member.
Example: Nested Structure
#include <iostream>
using namespace std;
struct Address {
string city;
string state;
};
struct Employee {
string name;
int id;
Address address; // Nested structure
};
int main() {
// Initialize structure
Employee emp = {"Alice", 101, {"New York", "NY"}};
// Display the values
cout << "Name: " << emp.name << endl;
cout << "ID: " << emp.id << endl;
cout << "City: " << emp.address.city << endl;
cout << "State: " << emp.address.state << endl;
return 0;
}
Output:
Name: Alice
ID: 101
City: New York
State: NY
Arrays of Structures
You can create arrays of structures to manage multiple instances of the structure.
Example: Array of Structures
#include <iostream>
using namespace std;
struct Student {
string name;
int rollNo;
float marks;
};
int main() {
// Array of structures
Student students[3] = {
{"John", 1, 85.5},
{"Jane", 2, 92.0},
{"Mike", 3, 78.8}
};
// Display details of each student
for (int i = 0; i < 3; i++) {
cout << "Name: " << students[i].name << endl;
cout << "Roll No: " << students[i].rollNo << endl;
cout << "Marks: " << students[i].marks << endl;
cout << endl;
}
return 0;
}
Output:
Name: John
Roll No: 1
Marks: 85.5
Name: Jane
Roll No: 2
Marks: 92.0
Name: Mike
Roll No: 3
Marks: 78.8
Passing Structures to Functions
Structures can be passed to functions by value or by reference.
Example: Passing by Reference
#include <iostream>
using namespace std;
struct Rectangle {
int length;
int width;
};
// Function to calculate area
int calculateArea(const Rectangle& rect) {
return rect.length * rect.width;
}
int main() {
Rectangle rect = {10, 5};
cout << "Area of rectangle: " << calculateArea(rect) << endl;
return 0;
}
Output:
Area of rectangle: 50
Structure Pointers
You can use pointers to access members of a structure.
Example: Structure Pointers
#include <iostream>
using namespace std;
struct Circle {
float radius;
};
int main() {
Circle c = {7.5};
Circle* ptr = &c;
cout << "Radius: " << ptr->radius << endl;
return 0;
}
Output:
Radius: 7.5
Real-Life Use Cases of Structures
- Employee Management Systems: Store employee details such as name, ID, and salary.
- Student Record Systems: Manage student details like name, roll number, and grades.
- Game Development: Represent game objects like players, enemies, and items.
- E-Commerce Applications: Store product details like name, price, and stock.
Advantages of Structures
- Custom Data Types: Group related data into one entity.
- Readability: Makes code cleaner and more understandable.
- Flexibility: Supports nesting and arrays.
Best Practices
- Use
struct
for Logical Grouping: Combine related variables into a structure. - Leverage Initialization: Use initialization for cleaner code.
- Consider Classes for Complexity: For advanced functionality, consider using classes instead of structures.
Explore More at The Coding College
Visit The Coding College to find in-depth tutorials and coding resources. Learn how to effectively use structures and other C++ features in your programming journey.