About Lesson
C++ Structures
In C++, structures (structs) allow you to group different data types together under a single name. They are used to create custom data types that can hold multiple variables of different types.
1. Declaring and Using Structures
Example of declaring and using a structure:
#include <iostream>
#include <string>
// Define a structure
struct Person {
std::string name;
int age;
double height;
};
int main() {
// Declare variables of type Person
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.height = 1.75;
// Accessing structure members
std::cout << "Name: " << person1.name << std::endl;
std::cout << "Age: " << person1.age << std::endl;
std::cout << "Height: " << person1.height << std::endl;
return 0;
}
2. Initializing Structures
Example of initializing a structure using constructor:
#include <iostream>
#include <string>
// Define a structure
struct Person {
std::string name;
int age;
double height;
// Constructor
Person(std::string n, int a, double h) : name(n), age(a), height(h) {}
};
int main() {
// Initialize structure using constructor
Person person2("Bob", 25, 1.80);
// Accessing structure members
std::cout << "Name: " << person2.name << std::endl;
std::cout << "Age: " << person2.age << std::endl;
std::cout << "Height: " << person2.height << std::endl;
return 0;
}
3. Array of Structures
Example of using an array of structures:
#include <iostream>
#include <string>
// Define a structure
struct Person {
std::string name;
int age;
double height;
};
int main() {
// Declare an array of type Person
Person people[3] = {
{"Alice", 30, 1.75},
{"Bob", 25, 1.80},
{"Charlie", 28, 1.70}
};
// Accessing elements of the array of structures
for (int i = 0; i < 3; ++i) {
std::cout << "Person " << (i + 1) << ":" << std::endl;
std::cout << "Name: " << people[i].name << std::endl;
std::cout << "Age: " << people[i].age << std::endl;
std::cout << "Height: " << people[i].height << std::endl;
std::cout << std::endl;
}
return 0;
}
Conclusion
Structures in C++ provide a way to group different data types together under a single name, allowing you to create custom data types tailored to your program’s needs. This chapter covered basic structure declaration, initialization, accessing structure members, and using arrays of structures. Understanding structures enables you to organize and manage related data more effectively in your C++ programs.
Join the conversation