Inheritance
Inheritance lets one class (the derived class) acquire the members and behavior of another class (the base class). It models an “is-a” relationship — a Circle is a Shape, a SavingsAccount is a BankAccount — and lets shared behavior live in one place instead of being duplicated across similar classes.
Basic syntax
class Derived : public Base
class Animal {
public:
std::string name;
Animal(std::string n) : name(n) {}
void eat() const {
std::cout << name << " is eating.\n";
}
};
class Dog : public Animal {
public:
Dog(std::string n) : Animal(n) {} // constructor chaining — see below
void bark() const {
std::cout << name << " says woof!\n";
}
};
int main() {
Dog d("Rex");
d.eat(); // inherited from Animal
d.bark(); // defined in Dog
}What gets inherited
A derived class inherits all of a base class's public and protected members. private members of the base class exist in the derived object's memory layout, but the derived class has no direct access to them — they can only be reached through the base class's own public/protected methods.
Constructor chaining
A derived class doesn't inherit constructors automatically — it must explicitly call a base-class constructor from its own member initializer list, exactly like Dog(std::string n) : Animal(n) does above. If you don't call one explicitly, the base class's default constructor is called implicitly before the derived class's own initializer list runs.
Method overriding
A derived class can provide its own version of a method that a base class already defines, replacing (overriding) that behavior for objects of the derived type.
Overriding a base class method
class Animal {
public:
void speak() const {
std::cout << "Some generic animal sound\n";
}
};
class Cat : public Animal {
public:
void speak() const { // overrides Animal::speak for Cat objects
std::cout << "Meow\n";
}
};
int main() {
Cat c;
c.speak(); // Meow — Cat's own version is used
}Types of inheritance
The access specifier used at the point of inheritance (public, protected, or private) controls how the base class's members appear in the derived class.
Inheritance type | public base members become | protected base members become |
|---|---|---|
| public | protected |
| protected | protected |
| private | private |
What's next
Inheritance is the mechanism; Polymorphism is the payoff — calling the right derived-class behavior through a base-class pointer or reference.