Chelsea
Chelsea

Reputation: 751

function overloading in c++ not working

When I run this program it produce error [Error] call of overloaded 'add(double, double, double)' is ambiguous.

Why is that? I mean the function argument has different datatype which is infact function overloading, then why error?

However when the float is replaced by double, it works fine.

#include<iostream>
using namespace std;

    void add(){
       cout<<"I am parameterless and return nothing";
    }

    int add( int a, int b ){
        int z = a+b;
        return z;
    }

    int add(int a, int b, int c){
         int z = a+b+c;
         return z;
    }

   int add(float a, float b, float c)
    {
         int z = a +b + c;
         return z;
    }

int main()
{
   cout<<"The void add() function -> ";
   add();
   cout<<endl;
   cout<<"add(2,3) -> "<<add(2,3)<<endl;
   cout<<"add(2,3,4) -> "<<add(2,3,4)<<endl;
   cout<<"add(2.1,4.5) -> "<<add(2.8,3.1,4.1)<<endl;

   return 0;
}

Upvotes: 3

Views: 312

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409442

Because you call a function using double literal, and those can be converted to either int or to float, and the compiler don't know which it should pick.

The easiest solution is to call the function with float literals instead:

add(2.8f,3.1f,4.1f)

Upvotes: 13

Related Questions