Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ interfaces and inheritance

I want to have an interface IA and another that extends it IB.

A then implements IA, and B inherits A and also implements IB.

However when compiling B gets errors saying the IA stuff is undefined, even though A defined it all :(

class IA
{
public:
    virtual ~IA(){}
    virtual void foo()=0;
};
class IB : public IA
{
public:
    virtual void bar()=0;
};


class A : public IA
{
public:
    A();
    void foo();
};
class B : public A, public IB
{
public:
    B();
    void bar();
};

error C2259: 'B' : cannot instantiate abstract class
due to following members:
'void IA::foo(void)' : is abstract

like image 984
will Avatar asked Apr 07 '11 13:04

will


2 Answers

Take a look at the C++ FAQ, from the following point onwards: https://isocpp.org/wiki/faq/multiple-inheritance#mi-diamond

It explains the "dreaded diamond" and virtual inheritance in some detail.

like image 128
NPE Avatar answered Oct 11 '22 13:10

NPE


(No, A does not define anything. You declared A() and void foo(), but you did not define them.)

The real problem is your multiple inheritance.

       B
     /   \
   A      IB
  /         \
IA          IA

As you can see, you have two "versions" of IA in your inheritance tree, and only A implements void IA::foo (though, as I noted above, this will give you a linker error as you didn't define the implementation).

void IB::IA::foo() remains unimplemented; thus, B itself "inherits the abstractness" and you can't instantiate it.

B will have to implement void foo() as well, or you might be able to use virtual inheritance to hack around it.

like image 22
Lightness Races in Orbit Avatar answered Oct 11 '22 14:10

Lightness Races in Orbit