A struct is a user-defined data type that groups related variables together. It’s used to represent a record or object.
struct Person {
string name;
int age;
bool isStudent;
};Person p1;
p1.name = "Alice";
p1.age = 22;
p1.isStudent = true;Person p2 = {"Bob", 30, false};This assigns values at the time of declaration.
Use the dot . operator to access fields:
cout << p1.name << endl;
cout << p1.age << endl;struct Address {
string city;
string country;
};
struct Employee {
string name;
Address addr;
};
Employee e;
e.name = "Charlie";
e.addr.city = "New York";One struct can contain another struct.
void printPerson(Person p) {
cout << p.name << ", Age: " << p.age;
}Structs can be passed to functions like regular variables.
In C++, struct is similar to class but has public members by default, while classes have private members by default.
Ask the AI if you need help understanding or want to dive deeper in any topic