Object-Oriented Programming (OOP)
C++ is a multi-paradigm language, but its OOP features are powerful. OOP allows you to model real-world entities (like aPlayer, Car, or File) as objects that contain both data and behavior.
1. Classes & Structs
A Class is a blueprint for creating objects. It encapsulates data (attributes) and functions (methods) that operate on that data. In C++,class and struct are almost identical. The only difference is default visibility:
- class: Members are
privateby default. (Used for complex objects with invariants). - struct: Members are
publicby default. (Used for simple data containers).
Access Modifiers
- public: Accessible from anywhere. The “interface” of your class.
- private: Accessible only from within the class. Used for internal state.
- protected: Accessible from the class and its derived classes (children).
2. Inheritance
Inheritance allows a class to derive properties and behavior from another. It promotes code reuse.3. Polymorphism
Polymorphism (“many shapes”) allows you to treat derived objects as base objects. This is the magic that lets you write flexible code. For example, you can have a list ofCharacter* pointers, some pointing to Wizards, some to Warriors. When you call attack(), the correct version is called for each object.
Virtual Destructors
Crucial: If a class has virtual functions, it must have a virtual destructor. This ensures that when you delete a base pointer, the child’s destructor is called, cleaning up its resources.4. Abstract Classes & Interfaces
A class is abstract if it has at least one pure virtual function (= 0). It cannot be instantiated. This is how C++ implements interfaces. It forces children to implement specific behavior.
5. The Rule of Five
In modern C++, if you manage resources manually (like raw pointers), you need to define 5 special member functions to handle copying and moving correctly.- Destructor: Cleans up resources.
- Copy Constructor: Creates a new object from an existing one (Deep Copy).
- Copy Assignment Operator: Assigns an existing object to another (Deep Copy).
- Move Constructor (C++11): “Steals” resources from a temporary object (Performance).
- Move Assignment Operator (C++11): Assigns by stealing resources.
Rule of Zero: If your class only uses RAII types (like
std::string, std::vector, std::unique_ptr), you don’t need to write ANY of these. The compiler defaults work perfectly. This is the goal.Summary
- Classes: Encapsulate data and behavior.
- Inheritance: Enables code reuse (
publicinheritance is “is-a”). - Polymorphism: Allows dynamic behavior via Virtual Functions.
- Abstract Classes: Define interfaces/contracts.
- Rule of Five: Implement copy/move semantics only if managing raw resources. Otherwise, follow Rule of Zero.