I have the following code:
#include <iostream>
class Grandma
{
public:
virtual void foo() = 0;
};
class Mom : public Grandma{};
class Dad
{
public:
void foo() { std::cout << "dad's foo impl"; }
};
class Me : public Mom, public Dad{};
int main()
{
Me m;
m.foo();
}
and getting : cannot instantiate abstract class
I know what this error means, I know I can’t instantiate Grandma because of pure-virtual.
But why can’t I instantiate Me, when compiler knows I am derived from Mom and Dad and Dad has foo implemented?
I know I can fixed it by adding foo into Me and inside it call e.g. Dad::foo, but I am afraid it is not solution for my case.
Is it really necessary to have virtual method implementation between its declaration and instantiated object (when traversing “class hierarchy graph”)? See ASCI graph
A
|
B1 B2
\ |
C1 C2
| /
|/
D
|
E
When I want to instantiate E and have virtual declaration in A, the only way to make it run is to define it in A, B2, C1, D or E?
and similarly when is virtual declaration in C2 only way is to define it in C2, D or E?
I know this may be silly question, but I had a loooong day and can not think anymore.
Please, do not answer just with – “It is not possible”, but try to add explanation why not.
Thank you!
EDIT — foo() in Dad is of course should not be private
There is no relation between
Dadclass andGrandmaclass.DadandGrandmaare two completely different classes. Given that the method inDadis not considered as an implementation of the pure virtual method inGrandmaand has to be implemented in theMeclass.When you derive from an Abstract class(class containing atleast one pure virtual function) the deriving class needs to override and implement ALL the pure virtual member functions of the Base Class. If not, the deriving class becomes Abstract too, same applies to the classes deriving from the derived class further down the hierarchy.