Overloading and Overriding

Overloading and Overriding

Overriding a method suppresses the visibility of any overloads in the base class for the overridden method. Say you have a base class CBase where there are two trivial overloads:

 class CBase { CBase (); Func (int param); Func (float param);};

In the derived class, you overload Func:

 class CDerived { CDerived (); Func (float param);};

Say you do something like this:

 CDerived derived;int param = 1;derived.Func (param);

You expect that CBase::Func (int) should be called as you have passed a parameter of type int and this method would be the best match. You’d be surprised.
If you run it in debug step by the step, you’ll see that instead CDerived::Func (float) is called. Why? Because when you override a method, all the overloads in the base class for that method become invisible. What happens is that a conversion from int to float is made for param and then CDerived::Func (float) is called. Perhaps not exactly what you wanted to do.
Here’s a workaround:
In CDerived, bring the overloads in the CDerived interface by using the C++ statement “using”.

 class CDerived { CDerived (); using CBase::Func; Func (float param);};

Now everything’s fine and the compiler will call CBase::Func (int) as you’d probably expected.


Share the Post: