Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 171 ยท Object-Oriented Programming

Access in Inheritance, Multiple and Virtual Inheritance

Learn C++ public, protected and private inheritance, multiple inheritance, the diamond problem, virtual inheritance and mixins, with runnable examples.

In Inheritance you wrote class Derived : public Base and got a class that is a Base with extra features. That public keyword is not decoration. C++ has three kinds of inheritance (public, protected and private), and each one changes who can see the base class's members and who can treat a Derived as a Base.

C++ also lets one class inherit from several base classes at once. That's powerful for combining independent capabilities, but it brings the famous diamond problem, which C++ solves with virtual inheritance. This lesson covers all of it: the three access modes, when private inheritance is useful (and when composition is better), multiple inheritance and its ambiguities, virtual bases and their construction rules, and the mixin pattern that uses inheritance to bolt small features onto a class.

The three access modes

The access keyword in the base list sets a ceiling on how visible the inherited members are from outside Derived. Members never become more visible than they were in the base, and private members of the base are never accessible in the derived class, whatever mode you choose.

Member in Base : public Base : protected Base : private Base
public public in Derived protected in Derived private in Derived
protected protected in Derived protected in Derived private in Derived
private not accessible not accessible not accessible

The mode also controls the conversion from Derived to Base. With public inheritance, any code can pass a Derived& where a Base& is expected. With private inheritance, only Derived itself (and its friends) knows that it is a Base. To everyone else the relationship is an implementation detail.

C++ public versus private inheritance

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.

Uncomment either of the last two lines and the compiler refuses: outside PrivateCar, the Engine part is hidden. Inside, everything works as before.

Two defaults are worth memorizing, because they're a frequent source of confusion:

  • class D : B (no keyword) means private inheritance.
  • struct D : B (no keyword) means public inheritance.

Always write the keyword explicitly. A reader shouldn't have to remember which default applies.

protected inheritance works like private inheritance, except that classes derived from Derived can still see the base. It's rare enough that many experienced developers have never needed it.

Private inheritance means "implemented in terms of"

Public inheritance models is-a: a Circle is a Shape, so it's fine for code to treat it as one. Private inheritance models something different: implemented in terms of. The derived class reuses the base's code, but it doesn't want to be one in the eyes of its users.

A classic illustration is a class built on top of a standard container. You choose which inherited members to expose again with using declarations:

C++ A recent-items list built with private inheritance

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 same class written with composition, holding a std::vector<std::string> items_; member and forwarding three functions, is just as short and is usually the better choice. Composition keeps the two types fully independent: RecentList doesn't inherit hundreds of names, it can't accidentally be converted to a vector by its own members, and you can swap the container later without touching anything else.

Reach for private inheritance only when composition can't do the job:

  • You need to override a virtual function of the base class, but you don't want users to see the base. A member object can't override anything. (Virtual functions are covered in Virtual Functions and Polymorphism.)
  • You need access to protected members of a class designed to be inherited from.
  • Empty base optimization used to be a reason (an empty base adds no size, while an empty member takes at least one byte). Since C++20, the [[no_unique_address]] attribute on a member gets the same saving with composition.

A good rule of thumb: use public inheritance for is-a relationships, composition for has-a and implemented-in-terms-of relationships, and private inheritance only when one of the special cases above forces your hand.

Multiple inheritance

A class can list several base classes, separated by commas. Each one can have its own access mode. The derived object contains a complete subobject for every base, and it can be converted to a reference to any public base.

Base classes are constructed in the order they appear in the base list, left to right, before the derived class's own members. Destruction runs in exactly the reverse order. The order in which you write the member initializer list doesn't matter, just as for members (GCC's -Wreorder warns when the two orders differ).

C++ Multiple inheritance and construction 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.

Notice how PortableRadio handles the name clash. Both bases declare name(), so without the derived class's own name(), the call device.name() would fail to compile with "request for member 'name' is ambiguous". C++ never picks one for you. You resolve the ambiguity by:

  • qualifying the call: device.Battery::name() or, inside the class, Radio::name(),
  • declaring your own member in the derived class (as above), which hides both,
  • or bringing one in with a using declaration: using Radio::name;.

The ambiguity is only reported when you actually use the name. Two bases with clashing names are perfectly legal as long as nobody calls the ambiguous member unqualified.

Where multiple inheritance shines (and where it doesn't)

Multiple inheritance works best when the bases are independent: they don't share state, don't share a common base, and each adds a separate capability. The most common real-world case is a class that implements several interfaces, small abstract classes with only pure virtual functions (see Abstract Classes and Interfaces). Inheriting several interfaces carries none of the problems below, because interfaces have no data.

It works badly when the bases overlap, which leads to the diamond.

The diamond problem

Suppose two classes both inherit from the same base, and a fourth class inherits from both of them. Drawn as a diagram, the inheritance graph looks like a diamond:

TEXT
        Device
       /      \
   Scanner   Printer
       \      /
     MultiFunction

With ordinary inheritance, Scanner contains a Device and Printer contains a Device, so MultiFunction contains two separate Device subobjects. Each has its own data. That's rarely what you want: a multifunction machine has one serial number, not two.

C++ The diamond without virtual inheritance

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 output shows Device being constructed twice, the two serial numbers drifting apart, and an object of 8 bytes: two 4-byte ints. Every access to serial must say which path it means, and the object can't even be converted to a Device&, because the compiler wouldn't know which Device you mean.

Virtual inheritance

The fix is to mark the shared base as virtual in the classes that sit directly on top of it: struct Scanner : virtual Device. A virtual base is shared: however many paths lead to it, the most-derived object contains exactly one subobject of it.

That raises a question: if Scanner and Printer both initialize Device differently, which one wins? Neither. The rule is that a virtual base is constructed by the most-derived class, the class of the actual object being created. The Device{...} initializers in Scanner and Printer are simply skipped when they're part of a MultiFunction. Virtual bases are also constructed first, before any non-virtual base.

C++ One shared base with virtual inheritance

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.

Device(999) runs once, before Scanner() and Printer(), and their own Device{100} and Device{200} initializers are ignored. A standalone Scanner still uses Device{100}, because there it is the most-derived class.

If MultiFunction didn't mention Device at all, the compiler would call Device's default constructor. Our Device has none, so that would be a compile error. This is the price of virtual inheritance: every class at the bottom of the hierarchy must know about, and initialize, virtual bases that may be several levels up.

Virtual inheritance has other costs too:

  • Objects get a hidden pointer (or offset table) so each subobject can find the shared base at run time, so they are larger and member access through the virtual base is slightly slower.
  • Converting a Device* back down to a Scanner* with static_cast is not allowed; you need dynamic_cast (see RTTI, dynamic_cast and typeid).
  • The hierarchy is harder to reason about, especially construction order.

The standard library itself uses a diamond: std::iostream inherits from both std::istream and std::ostream, which share a virtual base std::ios_base (through std::basic_ios). That's why a std::fstream has a single set of stream state flags. In application code, though, a diamond is often a sign that the hierarchy should be redesigned, for example by turning the shared base into an interface without data.

The virtual keyword must appear on every path to the shared base. If Scanner inherits virtual Device but Printer inherits plain Device, MultiFunction ends up with two Device subobjects again: one shared, one private to Printer.

Mixins: adding features with inheritance

A mixin is a small class whose only job is to add one capability to whatever class it's combined with: counting instances, logging, comparison operators, a name tag. Instead of building deep hierarchies, you mix several of them into a class.

In C++, mixins are usually templates. A common shape takes the class to extend as a template parameter and inherits from it, so you can stack mixins like layers. (Templates are covered in Function Templates; here you only need to read them.)

C++ Stacking mixins with templates

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.

Counted<Logged<Account>> is a class that inherits from Logged<Account>, which inherits from Account. Each layer's deposit does its bit and calls the layer below with Base::deposit. using Base::Base; inherits the constructors, so every combination can be built from an owner name. Two details are specific to templates: inside a template that inherits from a template parameter, you must write this->owner() (or Base::owner()) so the compiler looks the name up in the base.

These calls are resolved at compile time, with no virtual functions and no run-time cost. The related CRTP pattern (a class inheriting from a template instantiated with itself, like class Widget : public Counter<Widget>) is another popular way to write mixins; it's covered in Design Patterns in C++.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. class Box : Shape { }; uses which kind of inheritance?

    With the class keyword the default is private inheritance; with struct it is public. Always write the access keyword explicitly.
  2. 2. class Stack : private std::vector<int> declares no other bases. What happens when outside code passes a Stack to void f(std::vector<int>&)?

    With private inheritance, only Stack itself and its friends know it is a vector. Outside code can't convert it to the base class.
  3. 3. Scanner and Printer both inherit plain (non-virtual) Device, and MultiFunction inherits from both. How many Device subobjects does a MultiFunction contain?

    Without virtual inheritance each path has its own Device, so the object holds two copies, and unqualified access to Device members is ambiguous.
  4. 4. With virtual inheritance, which constructor initializes the shared virtual base Device in a MultiFunction object?

    Virtual bases are always initialized by the most-derived class, before any other base. Initializers for the virtual base in intermediate classes are skipped.
  5. 5. Battery and Radio both have a member function name(). PortableRadio inherits publicly from both and declares no name() of its own. What does radio.name() do?

    C++ never picks one base over another. You must qualify the call (radio.Radio::name()), add a using declaration, or define name() in the derived class.

Summary

  • The keyword in class D : public|protected|private B caps the visibility of inherited members and decides who may convert a D to a B. class defaults to private, struct to public; always write it out.
  • Public inheritance means is-a. Private inheritance means implemented in terms of, but composition is usually the better tool; use private inheritance mainly to override virtual functions or reach protected members.
  • With multiple inheritance, bases are constructed left to right in the base list and destroyed in reverse. Name clashes are errors only when used; resolve them with qualification, a using declaration or your own member.
  • A diamond without virtual gives two copies of the shared base. virtual inheritance shares one copy, which is constructed first and by the most-derived class.
  • Virtual inheritance costs size, speed and clarity. Prefer interfaces without data when several bases are needed.
  • Mixins add small features by inheritance; template mixins like Counted<Logged<Account>> stack layers with no run-time cost.

Next: Virtual Functions and Polymorphism, where a base class pointer finally calls the derived class's code.