Deukalion
Deukalion

Reputation: 2655

Implementation of inherited class' method (param=pointer to parent) in child class (param=pointer to child)

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

Answers (3)

Mike Seymour
Mike Seymour

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

Alok Save
Alok Save

Reputation: 206528

C++03 Standard: 10.3/2

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual an it overrides Base::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

Some programmer dude
Some programmer dude

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

Related Questions