Overriding non-virtual methods

Yep, you are misunderstanding a little.

The method of the same name on the derived class will hide the parent method in this case. You would imagine that if this weren’t the case, trying to create a method with the same name as a base class non-virtual method should throw an error. It is allowed and it’s not a problem – and if you call the method directly as you have done it will be called fine.

But, being non-virtual, C++ method lookup mechanisms that allow for polymorphism won’t be used. So for example if you created an instance of your derived class but called your ‘Display’ method via a pointer to the base class, the base’s method will be called, whereas for ‘vDisplay’ the derived method would be called.

For example, try adding these lines:

Base *b = &ba;
b->Display();
b->vDisplay();
b = &de;
b->Display();
b->vDisplay();

…and observe the output as expected:

Base: Non-virtual display.
Base: Virtual display.
Base: Non-virtual display.
Derived: Virtual display.

Leave a Comment