Classes and Structs

Classes and Structs

Bundle data with behavior, maintain invariants, and design small types cleanly.

Classes and Structs

Building a type

class BankAccount {
public:
    explicit BankAccount(double balance) : balance_{balance} {}

    void deposit(double amount) {
        balance_ += amount;
    }

    double balance() const {
        return balance_;
    }

private:
    double balance_{};
};

Why classes matter

They let you keep related data and rules together.

Key habits

struct vs class

Use struct for simple aggregates with obvious fields and little behavior. Use class when you need stronger encapsulation or invariants.

Rule of zero

If your members already manage themselves, let the compiler generate constructors, destructors, and assignment operators.

struct UserProfile {
    std::string name;
    std::vector<int> scores;
};

Modern value types

For many domain objects, a small value type with clear fields, comparisons, and no manual resource management is a better design than a large inheritance hierarchy.