Learning Hub Search Ctrl K

Legacy C++ › 3. Classes and Object-Oriented Programming

Inheritance

Public/protected/private inheritance and constructor/destructor order.

beginner #inheritance#base-class#derived-class#protected#access

Explanation

Inheritance lets a derived class reuse and extend a base class. Public inheritance models an is-a relationship: a Dog is an Animal, so a Dog can be used wherever an Animal is expected.

class Derived : public Base { ... };
  • Public members of Base stay public; protected stay protected; private are inaccessible to Derived.
  • private / protected inheritance are “implemented-in-terms-of” tools and hide the base interface.
  • Construction runs base first, then derived; destruction is the reverse.
  • The derived constructor selects the base constructor in its initializer list.
  • A derived member with the same name hides all base members with that name (even different overloads). Use Base::name or a using-declaration.

Example

#include <iostream>
#include <string>

class Animal {
protected:
    std::string name_;
public:
    explicit Animal(const std::string& n) : name_(n) { std::cout << "Animal(" << name_ << ")\n"; }
    ~Animal() { std::cout << "~Animal\n"; }
    void eat() const { std::cout << name_ << " eats\n"; }
};

class Dog : public Animal {
public:
    explicit Dog(const std::string& n) : Animal(n) { std::cout << "Dog\n"; }
    ~Dog() { std::cout << "~Dog\n"; }
    void bark() const { std::cout << name_ << " says woof\n"; }   // protected access
};

int main() {
    Dog d("Rex");        // Animal(Rex), Dog
    d.eat();             // inherited
    d.bark();
    Animal& a = d;       // derived-to-base conversion is implicit
    a.eat();
    return 0;            // ~Dog, ~Animal
}

Common pitfalls

  • Slicing: assigning a Dog to an Animal object (not reference/pointer) cuts off the derived part.
  • Without virtual, calling a member through a base pointer uses the base version (see Virtual Functions).
  • Deleting a derived object through a base pointer needs a virtual destructor. The example above is safe only because it deletes via the real type.
  • Do not use inheritance just to reuse code; prefer composition (a member object) when “is-a” does not hold.
  • Making data members protected couples derived classes to your representation.

Legacy vs modern

C++11 adds override and final to catch mistakes, and inheriting constructors with using Base::Base;.

Exercises

1. In what order do the constructors run for Dog d("Rex")?

Animal then Dog; destructors run ~Dog then ~Animal.

2. Is a Stack that inherits publicly from std::vector a good design?

Usually not: it exposes vector’s whole interface (violating the stack abstraction), and std::vector has no virtual destructor. Use a member instead.