Classes & Objects¶
Classes are the heart of Object-Oriented Programming (OOP) in C++. They encapsulate data and behavior into a single unit.
Class vs. Struct¶
In C++, class and struct are almost identical.
- class: Members are private by default.
- struct: Members are public by default.
Use struct for simple data containers (PODs) and class for objects with invariants and logic.
Access Specifiers¶
public: Accessible from anywhere.private: Accessible only from within the class.protected: Accessible from within the class and derived classes.
Static Members¶
Static members belong to the class itself, not to any specific object instance.
Static Variables¶
Shared across all instances. Must be defined outside the class (unless inline or constexpr).
Static Functions¶
Can be called without an object. Can only access static variables.
Unions¶
A union is a special class type where all members share the same memory location. Only one member can be active at a time.
Modern C++: Prefer std::variant over union for type safety.
Constructors & Destructors¶
- Constructor: Called when an object is created. Used to initialize invariants.
- Destructor: Called when an object is destroyed. Used to release resources (RAII).
Member Initializer Lists¶
Always use member initializer lists to initialize member variables. It is more efficient than assignment inside the constructor body.
Const Member Functions¶
If a member function does not modify the object, mark it as const. This allows it to be called on const objects.
The Rule of Five (Modern C++)¶
If you manage a resource (like a raw pointer), you likely need to define or delete these five special member functions:
- Destructor
- Copy Constructor
- Copy Assignment Operator
- Move Constructor
- Move Assignment Operator