Item 25. Emulating Multiple Inheritance

I l @ ve RuBoard

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   {   string DoName() { return "D";  }   };  

Demonstrate the best way you can find to "work around" not using multiple inheritance by writing an equivalent (or as near as possible) class D without using MI. How would you get the same effect and usability for D with as little change as possible to syntax in the calling code?

 *  *  *  *  * 

Starter: You can begin by considering the cases in the following test harness.

 void f1( A&  x ) { cout << "f1:" << x.Name() << endl; } void f2( B1& x ) { cout << "f2:" << x.Name() << endl; } void f3( B2& x ) { cout << "f3:" << x.Name() << endl; } void g1( A   x ) { cout << "g1:" << x.Name() << endl; } void g2( B1  x ) { cout << "g2:" << x.Name() << endl; } void g3( B2  x ) { cout << "g3:" << x.Name() << endl; } int main() {   D   d;   B1* pb1 = &d;   // D* -> B* conversion   B2* pb2 = &d;   B1& rb1 = d;    // D& -> B& conversion   B2& rb2 = d;   f1( d );        // polymorphism   f2( d );   f3( d );   g1( d );        // slicing   g2( d );   g3( d );                   // dynamic_cast/RTTI   cout << ( (dynamic_cast<D*>(pb1) != 0) ? "ok " : "bad " );   cout << ( (dynamic_cast<D*>(pb2) != 0) ? "ok " : "bad " );   try   {     dynamic_cast<D&>(rb1);     cout << "ok ";   }   catch(...)   {     cout << "bad ";   }   try   {     dynamic_cast<D&>(rb2);     cout << "ok ";   }   catch(...)   {     cout << "bad ";   } } 
I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net