๐ฅ C++ Inheritance: Complete Guide with Examples | Playlist
Playlist Link: C++ Series by TheCherno
๐ Introduction to Inheritance
Video Reference: Start at 0:00
Inheritance allows code reuse by creating a hierarchy of classes. A base/parent class (e.g., Entity) holds common functionality, and derived/child classes (e.g., Player) extend it with new features.
๐ ๏ธ Why Use Inheritance?
- Avoid code duplication (e.g.,
x,y,Move()inEntityandPlayer). - Create logical class relationships (e.g., โA Player is an Entityโ).
๐งฉ Example: Base Class (Entity)
Video Reference: 1:18
class Entity {
public:
float x, y;
void Move(float xa, float ya) {
x += xa;
y += ya;
}
};
Derived Class (Player)
Video Reference: 2:48
class Player : public Entity { // Inherit from Entity
public:
const char* name;
void PrintName() {
std::cout << name << std::endl;
}
};
โ What Player Inherits:
- All public/protected members of
Entity(x,y,Move()). - Can add new members (
name,PrintName()).
โ ๏ธ Key Points:
- Use
publicinheritance to preserve access modifiers. - No direct access to
privatemembers of the base class (useprotectedinstead).
๐ฅ๏ธ Using Inheritance in Code
Video Reference: 3:25
int main() {
Player player;
player.x = 5.0f; // Inherited from Entity
player.y = 3.0f;
player.Move(1.0f, -1.0f); // Inherited method
player.name = "Cherno"; // New member
player.PrintName(); // New method
}
๐ Memory Layout & Type Hierarchy
Video Reference: 5:00
- A
Playerobject contains all members ofEntity+ its own members. - Type Checking:
Player* player = new Player(); Entity* entity = player; // Valid (Player IS AN Entity)
๐ Common Pitfalls
- Access Specifiers:
- Use
protectedfor base class members if derived classes need direct access.class Entity { protected: // Accessible to derived classes float x, y; };
- Use
- Slicing:
- Storing a derived class object in a base class variable cuts off derived members.
Entity entity = player; // Only Entity members are copied!
- Storing a derived class object in a base class variable cuts off derived members.
๐ Key Takeaways
- Inheritance reduces code duplication by sharing common logic.
- Use
publicinheritance for โis-aโ relationships (e.g.,Playeris anEntity). - Derived classes extend base classes with new features.
๐ Full Video: Inheritance in C++
Need to revisit a concept? Jump directly to the video sections with the timestamped links above! ๐
