devxlogo

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.

See also  5 Tips for Working With an Onsite Interpreter
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist