O'Reilly logo

C++ For Dummies®, 6th Edition by Stephen R. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 25. Inheriting Multiple Inheritance

In This Chapter

  • Introducing multiple inheritance

  • Avoiding ambiguities with multiple inheritance

  • Avoiding ambiguities with virtual inheritance

  • Figuring out the ordering rules for multiple constructors

  • Getting a handle on problems with multiple inheritance

In the class hierarchies discussed in other chapters, each class inherits from a single parent. Such single inheritance is sufficient to describe most real-world relationships. Some classes, however, represent the blending of two classes into one. (Sounds sort of romantic, doesn't it?)

An example of such a class is the sleeper sofa that integrates a harsh bed into an uncomfortable sofa. To adequately describe a sleeper sofa in C++, the sleeper sofa should be able to inherit both bed- and sofa-like properties. This is called multiple inheritance.

Describing the Multiple Inheritance Mechanism

Figure 25-1 shows the inheritance graph for class SleeperSofa that inherits both from class Sofa and from class Bed.

Class hierarchy of a sleeper sofa.

Figure 25.1. Class hierarchy of a sleeper sofa.

The code to implement class SleeperSofa looks like the following:

// // MultipleInheritance - a single class can inherit from // more than one base class // #include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Bed { public: Bed(){} void sleep(){ cout << "Sleep" << endl; } int weight; }; class Sofa { public: Sofa(){} void ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required