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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With