C++ Struct

What is a Struct?

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;
};

Declaring Struct Variables

Person p1;
p1.name = "Alice";
p1.age = 22;
p1.isStudent = true;

Initializing Structs

Person p2 = {"Bob", 30, false};

This assigns values at the time of declaration.

Accessing Members

Use the dot . operator to access fields:

cout << p1.name << endl;
cout << p1.age << endl;

Nested Structs

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.

Structs and Functions

void printPerson(Person p) {
    cout << p.name << ", Age: " << p.age;
}

Structs can be passed to functions like regular variables.

Structs vs Classes

In C++, struct is similar to class but has public members by default, while classes have private members by default.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic