0

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

4
  • There is nothing which would result in such error. Are you sure this is exactly the code which is giving you said error?
    – Nitesh
    Mar 5, 2014 at 4:56
  • yes, I am compiling using VS 2005 C++ compiler and getting this error
    – atulya
    Mar 5, 2014 at 5:01
  • Getting same error with - gcc version 4.1.2 20080704 (Red Hat 4.1.2-46), also
    – atulya
    Mar 5, 2014 at 5:19
  • As I said there was no error with your initially posted question. Now you edited the call to func1 and changed the argument from with 9 to 9.9. This is certainly ambiguous as accepted answer has explained.
    – Nitesh
    Mar 6, 2014 at 3:46

1 Answer 1

3

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 ;).

1
  • 1
    I think it is worth to mention that 9.9 is a double literal. Mar 5, 2014 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.