3

I am passing different types of argument to the fun(), the code gets compiled, but still, the same function that prints "Class B" is getting executed. Shouldn't there happen overloading of functions? Why does this happen?

#include <iostream>
using namespace std;

class A
{
    public:
    void fun(int x)
    {
        cout<<"class A"<<endl;
    }

};

class B: public A
{
    public:
    void fun (char c)
    {
        cout<<"Class B"<<endl;
    }
};

int main()
{
    B obj;
    obj.fun('c');
    obj.fun(3);
}
miszcz2137
  • 894
  • 6
  • 18
Sandeep
  • 131
  • 9
  • Related: [https://stackoverflow.com/questions/411103/function-with-same-name-but-different-signature-in-derived-class](https://stackoverflow.com/questions/411103/function-with-same-name-but-different-signature-in-derived-class) – drescherjm Mar 07 '20 at 13:32

3 Answers3

4

B::fun() shadows A::fun() and an int literal is easily converted to char so your compiler had no difficulty with resolving that call. You can add using A::fun; to B's definition to make it visible.

bipll
  • 11,747
  • 1
  • 18
  • 32
4

When writing obj.fun(<argument>), first what fun to be called will be looked up. Since the compiler only looks at B first, it finds B::fun(char) both times, which is what is selected.

It would only look at A if there was no one parameter member function, so fun in B effectively hides fun in A. To overcome that, you can directly call A's fun like:

obj.A::fun('c');  // A
static_cast<A&>(obj).fun('c');  // A

Or you can bring A::fun(int) into B by using it:

class B: public A
{
public:
    using A::fun;

    void fun(char c)
    {
        std::cout << "Class B\n";
    }
};

obj.fun('c');  // B
obj.fun(3);  // A
Artyer
  • 31,034
  • 3
  • 47
  • 75
1

You cannot overload like this across a heirarchy.

Name lookup happens before overload resolution and access control.

Once a function name is found in B, other classes up the heirarchy will not be checked. So all the candidate functions for a particular function call would be the functions present in B.

You will have to make the function name in A visible in B by saying:

using A::foo;

inside class B.

Now the overload will work as you expect.

Suhail Khan
  • 190
  • 1
  • 1
  • 7