Inheritance
Overview
If you are coding a video game and create a Player class and an Enemy class, you will quickly notice they both have health, speed, and a move() function. Writing this identical code twice violates the DRY (Don't Repeat Yourself) principle.
Inheritance solves this. You create a 'Base Class' (or Parent) like Entity that holds the shared data. Then, you create 'Derived Classes' (Children) like Player and Enemy that 'Inherit' everything from Entity. The children automatically receive all the parent's variables and functions without writing a single line of code, but they can still add their own unique features.
Syntax
// 1. THE BASE CLASS (Parent)
class Entity {
public:
int health = 100;
void move() { std::cout << "Moving...\n"; }
};
// 2. THE DERIVED CLASS (Child)
// The colon ':' followed by 'public Entity' establishes the inheritance!
class Player : public Entity {
public:
int mana = 50; // Unique to Player
void castSpell() { std::cout << "Casting Magic!\n"; }
};
int main() {
Player p1;
// p1 inherited health and move() from Entity!
std::cout << "HP: " << p1.health << "\n";
p1.move();
return 0;
}Common Pitfalls
- The
privateinheritance trap. If you just writeclass Player : Entitywithout the wordpublic, C++ defaults toprivateinheritance. This means everything inherited from the Parent instantly becomes completely invisible and unusable to the outside world, breaking your code.
Interview Questions
protected access modifier and why it is crucial for Inheritance.If a Parent class has private variables, they are so secure that even its own Child classes cannot access them! If you want variables to be hidden from the public main() function, but still perfectly accessible to any Child classes that inherit from the Parent, you must use the protected modifier.
Real-World Example
Using the protected modifier to build a scalable class hierarchy.
#include <iostream>
class Vehicle {
protected: // Only Children can see this!
int speed = 0;
};
class Car : public Vehicle {
public:
void accelerate() {
speed += 10; // Allowed because speed is 'protected', not 'private'!
std::cout << "Speed: " << speed << "\n";
}
};Check Your Knowledge
Test your understanding of Inheritance with these quick questions.