Chapter 25. Emulating Multiple Inheritance

Difficulty: 5

If you couldn't use multiple inheritance, how would you emulate it? This exercise will help you to understand firsthand some of the reasons why multiple inheritance works the way it does in C++. In your answer, don't forget to emulate as natural a syntax as possible for the calling code.

Consider the following example:

class A
{
public:
  virtual ~A();
  string Name();
private:
  virtual string DoName();
};

class B1 : virtual public A
{
  string DoName();
};

class B2 : virtual public A
{
  string DoName();
};

A::~A() {}
string A::Name(){   { return DoName(); }
string A::DoName()  { return "A"; }
string B1::DoName() { return "B1"; }
string B2::DoName() {    return "B2"; }

class D : public B1, public B2
{

Get More Exceptional C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.