Classes and Structs
Classes and Structs
Bundle data with behavior, maintain invariants, and design small types cleanly.
Classes and Structs
Bundle data with behavior, maintain invariants, and design small types cleanly.
class BankAccount {
public:
explicit BankAccount(double balance) : balance_{balance} {}
void deposit(double amount) {
balance_ += amount;
}
double balance() const {
return balance_;
}
private:
double balance_{};
};
They let you keep related data and rules together.
constexplicitstruct vs classUse struct for simple aggregates with obvious fields and little behavior. Use class when you need stronger encapsulation or invariants.
If your members already manage themselves, let the compiler generate constructors, destructors, and assignment operators.
struct UserProfile {
std::string name;
std::vector<int> scores;
};
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.