C++: Overriding methods – problem with hiding overloads in the base class

What is the outcome of the simple program below?

#include <iostream>
#include <conio.h>

using namespace std;

class Base 
{
public:
   void DoSth(int tmp) 
   {
	   cout << "Base::DoSth(int)\n";
   }

   void DoSth(char tmp) 
   {
	   cout << "Base::DoSth(char)\n";
   }
};

class Derived : public Base
{
public:
   void DoSth(int tmp) 
   {
	   cout << "Derived:DoSth(int)\n";
   }
};

int main()
{
	Derived d;
	d.DoSth(5);
	d.DoSth('c');
   
	getch();
    return 0;
}

Answer

Derived:DoSth(int)
Derived:DoSth(int)

Surprised? If so, you probably chose:

Derived:DoSth(int)
Base::DoSth(char)

There's a tricky problem here, though. The reason why the code worked as it did is class Derived overrode only one method from Base class: Base::DoSth(int) and thus it hid the other overloads defined by class Base. This way, executing d.DoSth('c') actually invoked Derived::DoSth(int), casting char to int.

In order to get this output:

Derived:DoSth(int)
Base::DoSth(char)

class Derived must be defined as below:

class Derived : public Base
{
public:
   void DoSth(int tmp) 
   {
	   cout << "Derived:DoSth(int)\n";
   }
   using Base::DoSth;	// brings the other Base::DoSth overloads into scope
};

Please mind that using declaration was added: using Base::DoSth;. Check description of using declaration at MSDN to get more information if you are still lost.

0 Responses to “C++: Overriding methods – problem with hiding overloads in the base class”


  • No Comments

Leave a Reply