Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 171 ยท Object-Oriented Programming

Inheritance

Learn C++ inheritance - base and derived classes, constructor and destructor order, protected members, inheriting constructors, name hiding vs overriding, and final.

Inheritance lets you define a new class as an extension of an existing one. The new derived class automatically contains everything the base class has, its data members and its member functions, and adds or adjusts what it needs. A SavingsAccount is an Account that also earns interest; a Button is a Widget that can be clicked. Code written for the base class works with every derived class, because every derived object contains a complete base object.

C++ inheritance is powerful and has more knobs than in most languages: three kinds of access, multiple bases, and functions that are either statically or dynamically dispatched. This lesson covers the core that every C++ programmer uses daily: declaring derived classes, the order in which the pieces are constructed and destroyed, protected members, reusing base constructors, the difference between hiding and overriding a function, and final. Virtual functions, which make inheritance truly polymorphic, get their own lesson.

Base and derived classes

Write the base class after a colon, usually with the keyword public:

C++ A derived class extends a base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Key ideas:

  • SavingsAccount inherits deposit, balance and owner, and the private members owner_ and balance_. They're physically inside every SavingsAccount object, followed by its own rate_.
  • Private members are inherited but not accessible. SavingsAccount can't write balance_ += ...; it must use the public interface like everyone else. That's encapsulation working as intended.
  • A derived object can be used wherever a base reference or pointer is expected. That's the "is-a" relationship: every SavingsAccount is an Account.

public inheritance means the base's public members stay public in the derived class. protected and private inheritance exist too; they're rare and covered with multiple inheritance in Access in Inheritance, Multiple and Virtual Inheritance. Note that with the class keyword, inheritance is private by default, so always write public explicitly. With struct it's public by default.

What is and isn't inherited

A derived class inherits all data members and ordinary member functions, including overloaded operators (except assignment). It does not automatically get:

  • the base's constructors (unless you ask, see below) or its destructor; it gets its own,
  • the base's copy and move assignment operators; the derived class's own (possibly generated) ones call them,
  • the base's friends: friendship isn't inherited.

Static members are shared: there is still just one, and both Base::count and Derived::count name it.

Construction and destruction order

A derived object is built from the inside out, and taken apart in exactly the reverse order:

  1. Base class subobjects are constructed first (in the order the bases are listed),
  2. then the derived class's data members, in declaration order,
  3. then the derived constructor's body runs.

Destruction runs the destructor body first, then destroys members in reverse order, then the bases. This guarantees that while a constructor or destructor body runs, everything it might use already exists or still exists.

C++ Construction and destruction order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The base Vehicle is complete, including its own chassis_ member, before any part of Truck exists. Then Truck's members are built, then its body runs, and destruction mirrors all of it.

Members are always constructed in declaration order, whatever order the initializer list uses. If you wrote Truck() : Vehicle{6}, cargo_bed_{"cargo bed"}, cab_{"cab"}, cab_ would still be built first, and GCC would warn (-Wreorder, part of -Wall) that 'Truck::cargo_bed_' will be initialized after 'Part Truck::cab_'. The order matters as soon as one member's initializer uses another. Always write initializer lists in declaration order, with the base class first, so the code reads the way it runs. You saw the same rule in Constructors and Member Initializer Lists.

If you don't mention the base in the initializer list, its default constructor is called. If the base has none, as Vehicle doesn't here, leaving it out is a compile error.

protected members

private members are hidden even from derived classes, and public members are open to everyone. protected is in between: accessible to the class itself and to classes derived from it, but not to outside code.

C++
class Shape {
public:
    double area() const { return compute_area(); }
protected:
    explicit Shape(std::string name) : name_{std::move(name)} {}   // only for derived classes
    virtual double compute_area() const = 0;
    const std::string& name() const { return name_; }
private:
    std::string name_;
};

Two common, sensible uses:

  • Protected constructors for base classes that should never be created on their own.
  • Protected helper functions that give derived classes extra hooks without exposing them publicly.

Be cautious with protected data. Every derived class, including ones written years later by someone else, can modify it directly and break the base's invariants. A protected data member is almost as exposed as a public one. Prefer private data plus protected or public functions.

Reusing base constructors

When the derived class adds no data or only members with default initializers, writing forwarding constructors is tedious. using Base::Base; inherits the base's constructors:

C++ Inheriting constructors and calling base versions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Logger::log(...) with the qualified name calls the base class's version. It's how a derived function extends base behavior instead of replacing it.

Hiding vs overriding

AuditLogger::log above has the same name and signature as Logger::log, but Logger::log is not virtual. That means it isn't overridden, only hidden. The difference shows up as soon as you call through a base reference: the compiler decides which function to call from the static type of the expression, not the actual object.

And hiding goes further than you might expect: a function in the derived class hides every base function with the same name, regardless of parameters.

C++ Name hiding and static binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

What happened:

  • fancy.print(42) finds the name print in FancyPrinter and stops looking. The only candidate is print(double), and 42 converts to double. The base print(int) is never considered. This catches people constantly.
  • using Printer::print; brings the base overloads into the derived scope so they overload with the new one.
  • as_base.describe() calls Printer::describe, even though the object is a FancyPrinter. Non-virtual functions are bound at compile time.

If you want as_base.describe() to call the derived version, the base must declare it virtual, and the derived class should mark its version override:

C++
class Printer {
public:
    virtual ~Printer() = default;
    virtual void describe() const { std::println("I am a Printer"); }
};

class FancyPrinter : public Printer {
public:
    void describe() const override { std::println("I am a FancyPrinter"); }
};

Now the call is dispatched at run time to the actual object's version. override makes the compiler check that a matching virtual function really exists in a base, so a typo or a missing const becomes an error instead of an accidental hide. That's the subject of Virtual Functions and Polymorphism, together with the virtual destructor shown above.

final

final stops further inheritance, in two places:

C++
class Config final {            // no class may derive from Config
    // ...
};
// class MyConfig : public Config {};   // error: cannot derive from 'final' base

class Base {
public:
    virtual ~Base() = default;
    virtual void run();
};

class Middle : public Base {
public:
    void run() override final;  // classes derived from Middle can't override run()
};

Mark a class final when it isn't designed to be a base, for example because it has no virtual destructor. As a bonus, the compiler can turn virtual calls on a final class into direct calls ("devirtualization").

Converting between base and derived

Converting up the hierarchy is implicit and safe: Derived& โ†’ Base&, Derived* โ†’ Base*. Converting down needs a cast, and a wrong static_cast from Base& to the wrong derived type is undefined behavior. dynamic_cast checks at run time; see RTTI, dynamic_cast and typeid.

Watch out for copying a derived object into a base object (not a reference):

C++
SavingsAccount savings{"Lin", 1000.0, 0.03};
Account plain = savings;        // copies only the Account part: rate_ is sliced away

This is called object slicing. It's legal and sometimes intended, but usually a bug. Pass objects by reference or pointer, or use std::unique_ptr<Base>, to keep the whole object. Virtual Functions and Polymorphism shows why slicing matters most with virtual functions.

Multilevel and hierarchical inheritance

Inheritance shapes come in a few standard forms. Single inheritance is one base and one derived class. Multiple inheritance (several bases) has its own lesson. Two more shapes need no new syntax:

  • Multilevel: a chain, where a class derives from a class that itself derives from another (Animal โ†’ Dog โ†’ Puppy). Each level inherits everything accessible from all levels above it.
  • Hierarchical: one base with several derived classes (Shape โ†’ Circle, Rect, Triangle). This is the shape polymorphism uses most.
C++ A chain and a tree of classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Constructors run from the top of the chain down and destructors in the reverse order, as in Construction and destruction order. The limitations of inheritance follow from this: the derived class is tightly coupled to its bases (a change in Animal can break Puppy), long chains are hard to read because a member may be defined several levels away, and every level adds a place where a missing virtual destructor can cause trouble. When a chain grows past two or three levels, ask whether some levels should be members instead.

Inheritance vs composition

Inheritance models is-a. If a sentence with "is a" sounds wrong, or the derived class would have to disable base behavior, use composition (a member) instead:

Relationship Example Use
is-a, substitutable everywhere SavingsAccount is an Account public inheritance
has-a a Car has an Engine a member
implemented in terms of a Stack uses a std::vector a private member (not inheritance)

The classic warning is the square/rectangle problem: if Rectangle has independent set_width and set_height, a Square derived from it can't honor that contract without surprising code written for rectangles. Code that works with a base must keep working with every derived class (the Liskov substitution principle). Also avoid deriving from standard containers like std::vector: they have no virtual destructor and aren't designed as bases.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. class Car : public Vehicle with a member Engine engine_;. In what order are the parts of a Car constructed?

    Base classes are constructed first, then members in declaration order, then the constructor body. The order in the initializer list doesn't change this.
  2. 2. Base has void f(int). Derived declares void f(double). What does Derived d; d.f(5); call?

    Name lookup finds f in Derived and stops, so Base::f(int) isn't a candidate. 5 converts to double. A using Base::f; declaration would bring the base overload back.
  3. 3. Base has a non-virtual void show() const, and Derived defines its own show() const. What does const Base& b = derived; b.show(); call?

    Without virtual, the function is chosen at compile time from the type of the expression. Derived::show only hides Base::show; it doesn't override it.
  4. 4. What can a derived class do with a private data member of its public base class?

    Private members are inherited (they are part of every derived object) but not accessible. Use public or protected functions of the base, or make the member protected if that is truly appropriate.
  5. 5. What does Account plain = savings; do when savings is a SavingsAccount?

    plain is an Account object, so only the Account subobject is copied. The derived parts are sliced off. Use a reference or pointer to keep the full object.

Summary

  • class Derived : public Base makes every Derived contain a complete Base; derived references and pointers convert implicitly to base ones (is-a).
  • Private base members are inherited but inaccessible; protected opens members to derived classes only. Prefer private data with protected functions.
  • Construction goes bases โ†’ members (declaration order) โ†’ body; destruction is the exact reverse. Write initializer lists in that order.
  • Constructors aren't inherited unless you write using Base::Base;. Call a base version of a function with Base::function().
  • A derived function with the same name hides all base overloads (fix with using Base::name;); non-virtual calls are bound by static type. Only virtual + override gives run-time dispatch.
  • final blocks derivation or further overriding; copying a derived object into a base object slices it; use inheritance only for true is-a relationships.

Next: Access in Inheritance, Multiple and Virtual Inheritance, where you'll meet protected and private inheritance, multiple bases and the diamond problem.