Reputation: 2655
Say if I have an interface with virtual methods, but one of the arguments are:
virtual void Delete(ParentClass *parentClass) = 0;
If I later implement this in child class
void Delete(ChildClass *childClass)
{
};
...why doesn't this work as an implementation?
Upvotes: 0
Views: 235
Reputation: 254461
Because any type that's accepted as an argument for the base-class function, must also be acceptable by an override of that function. This prevents an error such as:
struct BastardClass : ParentClass {} wrong;
Delete(&wrong);
which, if dispatched to the override that expects a ChildClass
, would cause it to interpret the object as the wrong type.
(This is known as contravariance - arguments to a function overridden by a more specific type must be no more specific than those being overridden. For similar reasons, return types must be covariant - those specified by a function overridden by a more specific type must be no less specific.)
Upvotes: 0
Reputation: 206528
C++03 Standard: 10.3/2
If a virtual member function
vf
is declared in a classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name and same parameter list asBase::vf
is declared, thenDerived::vf
is also virtual an it overridesBase::vf
.
Note the text in bold.
An derived class function overides a Base class function only and only if it has the same signature as the Base class function with the exception of Co-Variant return types. Since your function Delete()
does not have the same signature in Base Class and Derived class, the derived class function is not overidding the Base class function but what you get is merely Function Hiding.
C++03 Standard: 3.3.7/1:
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class.
Upvotes: 0
Reputation: 409176
As the function prototype differs (one uses ParentClass
and the other ChildClass
) they are not the same functions. Instead the one with the ChildClass
argument is overloading and not overriding the Delete
function.
Upvotes: 1