Inheritance

Inheritance in C++: Every road vehicle shares certain paperwork: a registration number, a weight, an owner, a way to be taxed. A van adds a payload capacity.

The Analogy: The Vehicle Licence

Every road vehicle shares certain paperwork: a registration number, a weight, an owner, a way to be taxed. A van adds a payload capacity. A taxi adds a licence number and a meter. Nobody redesigns "vehicle" from scratch for each one — the specific type is a vehicle, plus extra.

Inheritance encodes that "is a". The base class holds what every version shares; each derived class adds only its own part. The test for whether inheritance is the right tool is a sentence: a van is a vehicle reads correctly, so Van : public Vehicle is sound. An engine is a vehicle does not read correctly — an engine is a part of one, and parts belong as members, not base classes.


Syntax or Core Structure

#include <iostream>
#include <string>

class Vehicle {
    std::string plate;                  // private: derived classes cannot touch it
protected:
    double weightKg;                    // derived classes may read and write
public:
    Vehicle(std::string reg, double kg) : plate(std::move(reg)), weightKg(kg) {}

    const std::string& registration() const { return plate; }
    double weight() const { return weightKg; }
    std::string describe() const { return "Vehicle " + plate; }
};

// "is a" -> public inheritance, spelled out.
class Van : public Vehicle {
    double payloadKg;
public:
    Van(std::string reg, double kg, double payload)
        : Vehicle(std::move(reg), kg),          // base is constructed first
          payloadKg(payload) {}

    double grossWeight() const {
        return weightKg + payloadKg;            // protected member: allowed
    }
    // Inherits registration(), weight() and describe() unchanged.
};

int main() {
    Van v{"AB12 CDE", 1800.0, 900.0};

    std::cout << v.registration() << "\n";      // AB12 CDE -- inherited
    std::cout << v.weight() << "\n";            // 1800     -- inherited
    std::cout << v.grossWeight() << "\n";       // 2700     -- Van's own
    std::cout << v.describe() << "\n";          // Vehicle AB12 CDE

    Vehicle& asVehicle = v;                     // a Van IS a Vehicle
    std::cout << asVehicle.weight() << "\n";    // 1800
    return 0;
}

Three rules visible above: the derived constructor must initialise the base in its member initialiser list, the base is fully built before the derived body runs, and a derived object may be used wherever the base is expected.


Technical Depth: What the Compiler Builds

A derived object contains a base object

Van in memory:
+-----------------------------+
| Vehicle part: plate, weight |   <-- constructed first, destroyed last
+-----------------------------+
| Van part: payloadKg         |
+-----------------------------+

So construction runs base-first and destruction runs derived-first:

class A { public: A() { std::cout << "A "; } ~A() { std::cout << "~A "; } };
class B : public A { public: B() { std::cout << "B "; } ~B() { std::cout << "~B "; } };

B b;            // prints  A B   ... then at end of scope:  ~B ~A

The order is not negotiable: the derived constructor's body may use base members, so the base must already exist.

The base must be constructible

If the base has no default constructor, the derived class must name it explicitly:

class Vehicle {
public:
    Vehicle(std::string reg, double kg);        // no default constructor
};

class Car : public Vehicle {
public:
    Car() {}                                    // ERROR: no matching Vehicle()
    Car(std::string reg) : Vehicle(std::move(reg), 1200.0) {}   // correct
};

C++11 lets you inherit the base's constructors wholesale when you add nothing new:

class Taxi : public Vehicle {
public:
    using Vehicle::Vehicle;         // Taxi now has every Vehicle constructor
};

Name hiding: the trap that catches everyone

A member declared in a derived class hides every base member of that name, regardless of signature:

class Base {
public:
    void log(int n);
    void log(const std::string& s);
};

class Derived : public Base {
public:
    void log(double d);            // hides BOTH base overloads
};

Derived d;
d.log(42);              // calls log(double) -- int converted!
d.log("hello");         // ERROR: no matching function
d.Base::log("hello");   // works, but ugly

One line fixes it: using Base::log; inside Derived restores the inherited overloads alongside the new one.

Redefining a base method is not overriding

class Vehicle {
public:
    std::string describe() const { return "a vehicle"; }        // NOT virtual
};
class Van : public Vehicle {
public:
    std::string describe() const { return "a van"; }            // hides, not overrides
};

Van v;
Vehicle& ref = v;
std::cout << ref.describe();        // "a vehicle" -- decided by the REFERENCE type

Without virtual, the call is resolved from the static type. Add virtual to the base and override to the derived and the output becomes "a van" — that is polymorphism, and it has its own lesson next module. For now: if a derived class is meant to change a behaviour, the base method must be virtual.

Object slicing

Assigning a derived object to a base object copies only the base part, silently:

Van v{"AB12 CDE", 1800.0, 900.0};
Vehicle sliced = v;                 // payloadKg is gone; virtual behaviour is lost

This is why polymorphic code always passes Base&, const Base& or Base* — never Base by value.

Access levels through inheritance

Base member: public Base: protected Base: private Base
publicpublicprotectedprivate
protectedprotectedprotectedprivate
privateinaccessibleinaccessibleinaccessible

Remember that class D : Base means private inheritance. Always write public.

Multiple inheritance and the diamond

A class may have several bases. The risk is inheriting the same base twice:

class Device { public: int serial{0}; };
class Printer : public Device {};
class Scanner : public Device {};
class MFD : public Printer, public Scanner {};   // TWO copies of Device

MFD m;
// m.serial = 1;                 // ERROR: ambiguous -- which Device?
m.Printer::serial = 1;           // must disambiguate

virtual inheritance collapses the duplicate, at the cost of extra indirection:

class Printer : virtual public Device {};
class Scanner : virtual public Device {};
class MFD : public Printer, public Scanner {};   // one shared Device

MFD m;
m.serial = 1;                    // now unambiguous

In practice, prefer inheriting from at most one class with data and any number of pure-interface classes.

final, and sealing a hierarchy

class Van final : public Vehicle { };       // nothing may inherit from Van

final on a class prevents further derivation; on a virtual method it prevents further overriding. Both document intent and let the compiler optimise.

Inheritance versus composition

QuestionInheritanceComposition
Relationship"is a""has a" / "uses a"
CouplingTight — derived depends on base internalsLoose — only the public interface
Can vary at runtimeNo, fixed at compile timeYes, swap the member
InterfaceInherited wholesale, including parts you dislikeYou choose what to expose

Default to composition. A Car that has an Engine and has a Gearbox is easier to change than one inheriting from both, and the classic warning sign is a derived class that inherits methods it must then disable.


Real World Example: A Staff Hierarchy

Shared payroll rules in the base, specialisations in the derived classes, and one composed member to show the alternative.

#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

// Composition: every employee HAS a contract. It is not a kind of employee.
struct Contract {
    std::string reference;
    int hoursPerWeek{37};
};

class Employee {
    std::string name;                       // private: the base owns its identity
    Contract contract;                      // composed member
protected:
    double annualSalary{0.0};               // derived classes adjust this
public:
    Employee(std::string who, Contract terms, double salary)
        : name(std::move(who)), contract(std::move(terms)), annualSalary(salary) {}

    virtual ~Employee() = default;          // a base meant for derivation

    const std::string& who() const { return name; }
    int hours() const { return contract.hoursPerWeek; }
    const std::string& contractRef() const { return contract.reference; }

    // Shared rule, defined once, used by every subclass.
    double monthlyGross() const { return annualSalary / 12.0; }

    double taxableMonthly() const {
        const double allowance = 12570.0 / 12.0;
        const double taxable = monthlyGross() - allowance;
        return (taxable > 0.0) ? taxable : 0.0;
    }

    // Overloaded pair in the base -- watch what Manager does to them.
    std::string summary() const { return name + " (" + contract.reference + ")"; }
    std::string summary(bool withPay) const {
        return withPay ? summary() + " " + std::to_string(monthlyGross()) : summary();
    }
};

class Engineer : public Employee {
    std::string specialism;
public:
    Engineer(std::string who, Contract terms, double salary, std::string field)
        : Employee(std::move(who), std::move(terms), salary),
          specialism(std::move(field)) {}

    const std::string& field() const { return specialism; }

    // Adds behaviour without touching anything the base promised.
    void awardCertification(double raisePercent) {
        annualSalary *= (1.0 + raisePercent / 100.0);    // protected member
    }
};

class Manager : public Employee {
    std::vector<std::string> reports;
public:
    using Employee::summary;                // keep BOTH base overloads visible

    Manager(std::string who, Contract terms, double salary)
        : Employee(std::move(who), std::move(terms), salary) {}

    void addReport(const std::string& person) { reports.push_back(person); }
    std::size_t teamSize() const { return reports.size(); }

    // A new overload. Without the 'using' above, this would hide the base pair.
    std::string summary(const std::string& prefix) const {
        return prefix + " " + Employee::summary() +
               ", team of " + std::to_string(reports.size());
    }
};

// Works for every kind of employee, present and future.
void payslip(const Employee& e) {
    std::cout << std::fixed << std::setprecision(2)
              << e.who() << " | " << e.hours() << "h | gross "
              << e.monthlyGross() << " | taxable " << e.taxableMonthly() << "\n";
}

int main() {
    Engineer ada{"Ada Lovelace", {"C-1001", 37}, 62000.0, "compilers"};
    Manager grace{"Grace Hopper", {"C-1002", 40}, 78000.0};
    grace.addReport("Ada Lovelace");

    payslip(ada);                           // base reference, derived object
    payslip(grace);

    ada.awardCertification(5.0);
    payslip(ada);                           // salary changed via protected member

    std::cout << grace.summary() << "\n";               // base overload, via 'using'
    std::cout << grace.summary("Lead:") << "\n";        // Manager's own overload
    std::cout << ada.field() << " " << grace.teamSize() << "\n";

    // Slicing: only the Employee part survives.
    Employee sliced = ada;
    std::cout << sliced.who() << " " << sliced.monthlyGross() << "\n";
    // sliced.field();                      // ERROR: the Engineer part is gone
    return 0;
}

The split between base and derived follows the "is a" test in both directions. An engineer is an employee, so Engineer : public Employee is sound and payslip can take a const Employee& that accepts every present and future subclass — write that function once and it never changes again. A contract, though, is not a kind of employee, so Contract is a member: composition for the "has a" relationship, inheritance for "is a". name stays private because no subclass has any business rewriting an identity, while annualSalary is protected precisely so Engineer::awardCertification can adjust it — the narrowest opening that makes the subclass's job possible. monthlyGross and taxableMonthly live in the base because the tax rule is identical for everyone; duplicating them in each subclass is how payroll bugs multiply. virtual ~Employee() = default is there because a class designed for derivation needs a virtual destructor, or deleting a derived object through a base pointer would skip the derived part. The using Employee::summary; line in Manager is doing real work: Manager declares its own summary(const std::string&), which would otherwise hide both inherited overloads and make grace.summary() fail to compile. Finally the deliberate slice at the end shows why polymorphic code passes references — Employee sliced = ada; copies only the base part and field() is simply gone.


Common Mistakes

  1. Writing class D : Base and getting private inheritance. Spell out public.
  2. Using inheritance for "has a". If you find yourself disabling inherited methods, you wanted composition.
  3. Forgetting to initialise the base in the derived constructor when the base has no default constructor.
  4. Assuming a redefined method overrides. Without virtual in the base, the call is resolved from the static type.
  5. Hiding base overloads by declaring one same-named member. Add using Base::name;.
  6. Omitting a virtual destructor on a base that is deleted through a base pointer. The derived part never runs its destructor.
  7. Passing a derived object by value as a base. Slicing discards the derived part and any virtual behaviour.
  8. Making base data protected out of habit. Every subclass then depends on that field's name and type forever.
  9. Deep hierarchies. Four or five levels means a change anywhere ripples everywhere. Two or three is plenty.
  10. Multiple inheritance from two classes that both hold data, producing ambiguities or a diamond.

Best Practices

  • Apply the "is a" test out loud before choosing inheritance; default to composition otherwise.
  • Always write the inheritance specifier, and make it public.
  • Give any class intended as a base a virtual destructor, and mark leaf classes final.
  • Keep base data private and offer protected functions when subclasses need controlled access.
  • Write using Base::method; whenever a derived class adds an overload of an inherited name.
  • Put shared rules in the base once, and let subclasses add only what is genuinely theirs.
  • Pass polymorphic objects by const Base& or Base*, never by value.
  • Use using Base::Base; to inherit constructors when the derived class adds no new members.
  • Keep hierarchies shallow and wide rather than deep.

Practice Exercises

  1. Build the hierarchy: Write Shape with a name and a const describe(), then Square and Triangle deriving from it, each adding its own dimensions and an area(). Write one function taking const Shape& and call it with both.
  2. Watch the order: Give a three-level hierarchy A -> B -> C constructors and destructors that each print their letter. Create one C inside a block, predict the six lines of output before running, then check.
  3. Spring the hiding trap: Give a base two print overloads (int and const std::string&) and a derived class a print(double). Call all three on a derived object, paste the error, then fix it with using and confirm all three now work.
  4. Slice it: Create an Engineer, assign it to an Employee variable by value, and try to call field(). Record the error, then repeat with an Employee& and explain in a comment what the reference preserved that the copy did not.