Populating abstract class members based on a concrete class
Let's say I have an interface that inherits from another interface (pure abstract class)
class BaseInterface
{};
Then another interface builds on BaseInterface
class ExtendedInterface : public BaseInterface
{};
Now I have a concrete class that implements BaseInterface:
class Base : public BaseInterface
{};
Now I want to implement ExtendedInterface, but since I already have Base, I want to fill the base elements of the BaseInterface with the base. For example:.
class Extended : public ExtendedInterface, public Base
{};
This does not work. I am getting complaints that I cannot create an instance since it is an abstract class. The only way I can make it work is to use virtual inheritance, but then I get warnings about inheritance using dominance.
source to share
What's the problem?
With your multiple inheritance Extended
inherits twice from BaseInterface
. This means that there are two independent entities BaseInterface
:
-
one is inherited through a concrete class
Base
that overrides all pure virtual functions. -
but the other is inherited with a class
ExtendedInterface
that is still abstract.
As a result, since some subobjects Extended
still have pure virtual functions, your class is still an abstract class that cannot be instantiated.
How to solve it?
As despite multiple inheritance, you seem to expect to have only one BaseInterface
, you need to use virtual inheritance:
class BaseInterface
{ virtual void test()=0; }; // abstract class
class ExtendedInterface : public virtual BaseInterface // virtual inheritance
{}; // abstract class
class Base : public virtual BaseInterface // virtual inheritance
{ void test() override {} }; // concrete class
class Extended : public ExtendedInterface, public Base // multiple
{}; // thanks to virtual inheritance, concerete class
With this logic to Extended
be the only one BaseInterface
with a redefined virtual functions, and you can create it.
Here's an online demo
source to share