Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function overloading in c++ not working

Tags:

c++

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;
}
like image 783
Chelsea Avatar asked May 10 '26 09:05

Chelsea


1 Answers

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)
like image 79
Some programmer dude Avatar answered May 12 '26 22:05

Some programmer dude