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 Initializers (Modern C++)¶
In Modern C++, you can (and should) initialize members where they are declared. This ensures they always have a valid default value.
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 Zero (Best Practice)¶
The best way to manage resources is not to manage them manually.
If your class relies on standard types like std::string, std::vector, or std::unique_ptr, you do not need to write a destructor, copy constructor, or assignment operator. The compiler generates them correctly for you.
The Rule of Five¶
Only if you are writing a low-level RAII wrapper (e.g., handling a raw file handle), you need to implement all five special members:
- Destructor
- Copy Constructor
- Copy Assignment Operator
- Move Constructor
- Move Assignment Operator
Prefer Rule of Zero whenever possible.