C++ ยท Chapter 36 of 49

C++ Inheritance

Inheritance lets a class (derived/child) reuse and extend the members of another class (base/parent), written as `class Dog : public Animal { ... };`. The derived class automatically gets the base class's public and protected members.

This promotes code reuse: shared behaviour lives in the base class, while each derived class adds or overrides only what makes it different.

Base and derived classes

`class Animal { public: void eat() {...} };` and `class Dog : public Animal { public: void bark() {...} };` โ€” a Dog object can call both eat() and bark().

Constructors in inheritance

A derived class's constructor can call the base class constructor explicitly using an initialiser list, e.g. `Dog() : Animal() {}`, to pass setup data upward.

Example 1 (cpp)
class Animal {
public:
    void eat() { std::cout << "Eating "; }
};
class Dog : public Animal {
public:
    void bark() { std::cout << "Woof"; }
};
int main() {
    Dog d;
    d.eat();
    d.bark();
}
Output
Eating Woof

Dog inherits eat() from Animal and adds its own bark() method.

Key points

  • class Derived : public Base establishes inheritance.
  • Derived classes gain public/protected members of the base.
  • Inheritance promotes code reuse across related classes.
  • Derived class constructors can invoke the base constructor.
๐Ÿ’ก Note: Prefer composition over inheritance when the relationship isn't truly an 'is-a' relationship.

๐Ÿ“ Quick Quiz

1. Which syntax makes Dog inherit from Animal?

2. What does a derived class inherit by default with 'public'?

3. Inheritance is mainly used for: