atulya
atulya

Reputation: 539

Ambiguous call to overloaded function in Base class

I have a class A with overloaded functions and derived class with overridden function.

class A
{
public:
    virtual void func1(float)
    {
        cout<<"A::func1(float) "<< endl;
    }
    void func1(int)
    {
        cout<<"A::func1(int) "<< endl;
    }
};

class B: public A
{
public:
    //using A::func1;

  void func1(float)
  {
      cout << " B::Func1(float)" << endl;
  }
};

int main()
{
    B obj;
    A obj1;

    obj.func1(10);
    obj1.func1(9.9);   // Getting error in call

    return 0;
}

error C2668: 'A::func1' : ambiguous call to overloaded function

Could anyone explain?

Thanks

Upvotes: 0

Views: 1078

Answers (1)

Whoami
Whoami

Reputation: 14408

The value 9.9 can be converted to either integer, or float as your interface. Hence it is finding ambiguity that which function to invoke:

You can mention explicit conversion like :

obj1.func1((float)9.9);   

or

obj1.func1((int)9.9)

Consider the below simple test code:

#include <iostream>

using namespace std;


void test(int a)
{
  cout <<" integer "<<a<<endl;
};


void test(float a)
{
  cout <<"Float "<<a<<endl;
}

int main ()
{
   test(10.3);
}

Try Commenting any one of the function above, it will work perfectly, where as, if you introduce both the functions, as in your code, you see ambiguity.

Hope this helps a bit ;).

Upvotes: 3

Related Questions