Search code examples
c++pointersreferenceoverloadingsqrt

c++ overload 3 function with different parameters(int,*int,&int)


So i have this homework to do "Using functions overloading define 3 functions with the same name but with different prams type (int, int*, int&) that will return the square root of the value." Well i made it but i don't know it gives me this error:"ambiguous call to overloaded function". I try to fix it but no succes... Here's my code it's quite simple:

#define _CRT_SECURE_NO_WARNINGS
#include <math.h>
#include <iostream>
using namespace std;

double rad(int);
double rad(int*);
double rad(int&);

int main(){
int a,*pt=&a;
cin>>a;
cout<<"Radical din "<<a<<" este "<<rad(a)<<endl;
cout<<"Radical din "<<a<<" este "<<rad(pt)<<endl;
cout<<"Radical din "<<a<<" este "<<rad(&a)<<endl;
return 0;
}

double rad(int x){
    return  (sqrt(x));
}
double rad(int *x){
    return  (sqrt(*x));
}
double rad(int &x){
    return  (sqrt(x));
}

Solution

  • Given these declarations:

    double rad(int);   // (1)
    double rad(int*);  // (2)
    double rad(int&);  // (3)
    

    Dealing with (2) is easy. We either have a pointer, or we don't, there's no possible confusion. The question then is, what happens with:

    int a;
    rad(a);
    

    Well, here both (1) and (3) work. And there's actually no preference between the two anywhere in the rules for determining what the best viable candidate is! It's an ambiguous call, so this will always fail to compile.


    Note that it is possible to explicitly call (1) though - by simply passing in an int that you can't take a reference to:

    rad(4); // calls (1), since neither (2) nor (3) are possible
    

    Note also that it is possible to call (1) or (3) even with a named variable like a, but we can't rely upon overload resolution to do it. We have to explicitly tell the compiler which function we want. And to do that, we have to cast the name:

    int a;
    static_cast<double(*)(int)>(rad)(a);  // calls (1) explicitly
    static_cast<double(*)(int&)>(rad)(a); // calls (3) explicitly