NaSh
NaSh

Reputation: 665

Virtual function implementation and multiple inheritance

I have a class F which needs to implement two functions f() and g(). I use two different class to implement these function.

class Base {public: virtual void f(); virtual void g(); };
class A : public virtual Base { void f(){/***/} };
class B : public virtual Base { void g(){/***/} };

f() needs to call g() or vice versa, which would be fine using this design. I need to have several implementation for A and B classes, let's say A1 and A2, B1 and B2. For example if I want to use A1 and B2 implementation:

class Test : public A1, public B2 {}; 

My Question is: How can I select implementation in run-time? If I want to create an object of class Test and want to select A and B class based on a parameter in my main function, how can I do that?

Upvotes: 1

Views: 395

Answers (2)

Frerich Raabe
Frerich Raabe

Reputation: 94319

Don't use inheritance, rather pass the object to delegate to in the constructor:

class Test : public Base
{
  Base *impl;
  public:
    Test( Base *impl ) : impl( impl ) { }

    virtual void f() { impl->f(); }
    virtual void g() { impl->g(); }

    // assignment operator, copy ctor etc.
};

In your main function you can then do

int main() {
   // ...
   Test *t;
   if ( someCondition ) {
     t = new Test( new A() );
   } else {
     t = new Test( new B() );
   }
   t->f();
   t->g();
}

Upvotes: 2

c-smile
c-smile

Reputation: 27460

With virtual classes the only feasible option would be to define all possible permutations like:

class TestA1B1 : public A1, public B1 {}; 
class TestA1B2 : public A1, public B2 {}; 
...

and to have some fabric function like this

Base* create(int p1, int p2) {
  if( p1 == 1 && p2 == 1 )
    return TestA1B1();
  else if( p1 == 1 && p2 == 2 )
    return TestA1B2();
  ...
  return nullptr; 
}

But I would consider set of free functions instead

void f_a1(Base* ptr);
void g_b1(Base* ptr);

and store pointers to them in Base.

Upvotes: 1

Related Questions