Lesson 17 — Object-Oriented Programming

Inheritance

Inheritance lets a class acquire the attributes and methods of another class, enabling code reuse and modelling natural "is-a" relationships between types.

Base and Derived Classes

The class being inherited from is the base class; the class that inherits is the derived class. The derived class automatically gains the base class's public and protected members, and can add its own on top.

C++ — Inheritance
class Animal {
public:
    std::string name;

    Animal(std::string n) : name(n) {}

    void eat() {
        std::cout << name << " is eating." << std::endl;
    }
};

class Dog : public Animal {
public:
    Dog(std::string n) : Animal(n) {} // call base constructor

    void bark() {
        std::cout << name << " says Woof!" << std::endl;
    }
};

int main() {
    Dog d("Rex");
    d.eat();  // inherited from Animal
    d.bark(); // defined in Dog
    return 0;
}

protected Members

A base class member marked protected is accessible to derived classes but hidden from outside code, striking a balance between full encapsulation and giving subclasses the access they need to extend behaviour.

Common Mistakes

  • Forgetting to call the base class's constructor explicitly when it requires parameters.
  • Making everything public in the base class just so derived classes can reach it, when protected is usually the better fit.
  • Assuming private base-class members are accessible in a derived class — they are not, even through inheritance.
  • Overusing inheritance to model relationships that are really "has-a" rather than "is-a" (composition is often the better tool).

Professional Tip

Ask "is a" before reaching for inheritance: a Dog is an Animal, so inheritance fits. A Car has an Engine, so composition (storing an Engine object as a member) is the better model, even though both involve one class using another.

Your Turn

Create a base class Shape with a protected double sideLength and a method describe(). Create a derived class Square that adds a getArea() method using sideLength. Instantiate a Square and call both describe() and getArea().

Mini Quiz

In C++, what is the class being inherited from called?