Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance in c++ with virtual functions

I have this code:

class A
{
public:
   virtual void FA()=0;
};

class B: public A
{
public:
    virtual void FB()=0;
};

class Imp_A: public A
{
public:
   void FA()
   {
      // implement FA
   }
};

class Imp_B :public Imp_A, public B
{
   public:
       void FB()
       {
           // implement FB by calling FA()
           FA();
           // do some more work here.
        }
};

in class Imp_B, I don't want to implement FA as it is already implemented in Imp_A which this class is based.

But when I try to compile my code, I am getting error that Imp_B is virtual and can not be instantiated.

also when I try to call FA inside FB, I am getting error that FA is ambiguous.

How can I solve this problem?

Please note that Imp_A is based on A and implement it, Imp_B is based on Imp_A and B and the idea is that it uses implementation of A from imp_A and only implement B.

like image 333
mans Avatar asked Oct 31 '25 20:10

mans


1 Answers

This looks like the classic "diamond inheritance problem" where you have a virtual method defined in a base class which is inherited by two or more other classes which are used as source for multiple inheritance.

Anyway - virtual inheritance is the answer to your problem

class A
{
public:
   virtual void FA()=0;
}

class B: virtual public A
{
public:
    virtual void FB()=0; //probably a pure virtual function as well!?
}

class Imp_A: virtual public A
{
public:
   void FA()
   {
      // implement FA
   }
}

class Imp_B :public Imp_A, public B //since you call FA() you need it's implementation from Imp_A
{
   public:
       void FB()
       {
           // implement FB by calling FA()
           FA();
           // do some more work here.
        }
}

The problem here is that Imp_b ends up with to definition for FA coming from two class A definitions; using virtual inheritance helps solve this issue.

like image 114
Pandrei Avatar answered Nov 03 '25 10:11

Pandrei