That's the very purpose of the virtual functions: to allow polymorphism.
Consider, for instance the following code
void draw_shapes( Shape * sh[], size_t count)
{
for ( size_t n = 0; n < count; ++n)
sh[n]->draw_myself();
}
every item of the array (every
Shape
) will draw itself depending on its real nature: a
Circle
and a
Rectangle
, for instance, will produce quite different drawings.
[Update]
Quote:
There is still a little confusing part. The inheritance relationship of the current classes is "Fir <- Sec <- Thi". If the virtual function is called, is the thi class's mFunc () function last overridden so that the same result is output all three times?
Every object performs its own
mfunc
code, even if the pointer declaration specifies the base class. Try:
int main()
{
Fir * p[] = { new Fir(), new Sec(), new Thi()};
for ( size_t n = 0; n < 3; ++n)
p[n]->mfunc();
for ( size_t n = 0; n < 3; ++n)
delete p[n];
return 0;
}
[/Update]