There is somewhat odd sample given in one of the Microsoft documentation pages , which consists of two classes, one is a base class and another one is a derived. The base class has the following virtual function member:
virtual void setEars(string type) // virtual function
{
_earType = type;
}
And another, defined in the derived class, which, as stated in comments, redefines the virtual function:
// virtual function redefined
void setEars(string length, string type)
{
_earLength = length;
_earType = type;
}
These two have different signatures and I haven't ever heard if you actually can redefine a virtual function with a function of a different signature. I compiled this sample and could not find any overriding behavior between these two. Is the sample just misleading or I'm missing something?
Is the sample just misleading or I'm missing something?
This example is indeed misleading. When overriding a virtual function in a derived type, it must come with the same signature as it is defined in the base class. If that is not the case, the function in the child class will be considered as its own entity and is not considered in a polymorphic function call. Additionally, it will hide the name of the base classes function, which is considered bad practice, as it violates the "is-a" relationship in public inheritance.
In order to prevent such accidental hiding, C++ introduced the override
keyword. When overriding a virtual function, it then must have a matching signature, otherwise, the compiler will reject it.