When a member function is declared virtual
in a base class, it will be virtual
for all child classes as well. The fact that you can omit the virtual
keyword in the child classes does not imply it is not virtual.
Your assumption on the code you proposed, that follows:
int main()
{
B* i;
i = new C();
i.get();
return (0);
}
are misguided by the fact that the above code won't even compile (even if you added the semicolons at the end of each class declaration/definition).
When you are dealing with pointers and you want to call a member function you can either dereference the pointer and use the .
operator:
(*ptr).function();
or use the ->
operator:
ptr->function();
Your code does neither of them. But assuming what you actually meant was:
int main()
{
B* i = new C();
i->get();
}
you assumptions turns out to be right:
- if
A::get
is virtual, in i->get
, C::get
will be called
- otherwise
B::get
will be called.
Why do I not need to put virtual on B::get()
to use C::get()
with B.get()
?
You don't. The void get()
member function is virtual from the base class, all the way to the C
class. You don't need to repeat the virtual
keywords, but I'd actually recommend it.