Topic 54 of 83
Inheritance
Overview
Inheritance allows a new class (derived) to inherit properties and behaviors from an existing class (base). This promotes massive code reuse. C++ supports various inheritance architectures.
Syntax
cpp
class Animal { /* Base */ };
// 1. Single
class Dog : public Animal {};
// 2. Multilevel
class Puppy : public Dog {};
// 3. Multiple
class Bird { /* Base 2 */ };
class FlyingDog : public Animal, public Bird {}; // Inherits from bothCommon Pitfalls
- Abusing inheritance when 'Composition' (a 'has-a' relationship) would be better than Inheritance (an 'is-a' relationship).
Interview Tips
- Explain the 'Diamond Problem'. If Class B and C inherit from A, and Class D inherits from B and C, D gets TWO copies of A. This is solved using 'virtual inheritance' (`class B : virtual public A`).
Real-World Example
Basic Single Inheritance for a game character.
example
cpp
#include <iostream>
using namespace std;
// Base class
class Entity {
public:
int x = 0, y = 0;
void move() { cout << "Moving...\n"; }
};
// Derived class
class Player : public Entity {
public:
void attack() { cout << "Attacking!\n"; }
};
int main() {
Player p;
p.move(); // Inherited
p.attack(); // Specific to Player
return 0;
}