I would like to better understand how the virtual
qualifier is propagated in a class family. Consider the following code:
struct Parent {
void func() { cout << "Parent!" << endl; }
};
struct Child : Parent {
void func() { cout << "Child!" << endl; }
};
int main() {
Parent* pc = new Child;
pc->func(); // prints "Parent!"
}
The Child
override of func()
is not called because the Parent
function is not virtual
. Simple enough.
In the following example, I added an interface to Parent
and I don't understand why adding it bound the call from Parent::func()
to Child:func()
since this last one is called from a Parent
pointer.
struct Interface {
virtual void func() = 0;
};
struct Parent : Interface {
void func() { cout << "Parent!" << endl; }
};
struct Child : Parent {
void func() { cout << "Child!" << endl; }
};
int main() {
Parent* pc = new Child;
pc->func(); // prints "Child!"
}
I was thinking that the construction of new Child
would go in the following order :
Interface
in constructed, declaring a pure virtualfunc()
Parent
is constructed, overridingfunc()
(I thought that at this point, the abstract construction would be "satisfied" and "done")Child
is constructed, declaring it's ownfunc()
implementation