Let's say I've got the following class hierarchy, wherein I have an interface and then further specializations of that interface that guarantee more functionality:
class parent_interface {
public:
virtual void foo() = 0;
};
class child1_interface : public parent_interface {
public:
virtual void bar() = 0;
};
class child2_interface : public parent_interface {
public:
virtual void baz() = 0;
}
And then I have concrete classes that provide that functionality:
class parent : public parent_interface {
public:
void foo() override;
};
class child1 : public parent, public child1_interface {
public:
//using parent::foo; ??
void bar() override;
};
The problem is if I try to instantiate a child1 object, I get a compiler error that
cannot declare field
instantiation_name
to be of abstract type because the following virtual functions are pure within child1: void foo()
I can fix this by creating a method within child1 called foo, that just calls parent::foo, but I'm wondering if there is a cleaner solution to this problem.
You need to specify virtual
inheritance, so that the compiler knows to combine the base classes back into one. This should compile for you (see it work):
class parent_interface {
public:
virtual void foo() = 0;
};
class child1_interface : public virtual parent_interface {
public:
virtual void bar() = 0;
};
class parent : public virtual parent_interface {
public:
void foo() override
{
}
};
class child1 : public parent, public child1_interface {
public:
//using parent::foo; ??
void bar() override
{
}
};
For more information, you can read about Virtual Base Classes here.