dominique120
dominique120

Reputation: 1302

What does "Cannot overload functions distinguished by return type alone" mean?

I have this code:

In the header:

...
int32_t round(float v);
...

and in the source

...
int32_t round(float v)
{
    int32_t t = (int32_t)std::floor(v);
    if((v - t) > 0.5)
        return t + 1;

    return t;
}
...

I've looked around here on this site but the examples seem a bit too complicated to me.

I'm learning C++ so if someone could explain to me what the error means and why it's occurring I would be grateful.

Upvotes: 22

Views: 94527

Answers (3)

Jack
Jack

Reputation: 133629

Function overloading means to have multiple methods with the same name.

Now, the compiler, to resolve the correct overloaded method, looks at method name and arguments but NOT at the return value. This means that if you have

int round(float something) { ... }
float round(float something) { ... }

Then the compiler is not able to distinguish them and know which one you want to invoke at a call point. So in your case this means that there is already another round method which accepts a float.

Upvotes: 51

sam
sam

Reputation: 866

C++ standard doesn't support overloading based on return type alone, it's because the return type doesn't play a role in determining the function being called. The return type is only determined at runtime, and thus it's not part of the function signature which is used by the compiler to decide which function to call.

Upvotes: 2

Saurabh Yadav
Saurabh Yadav

Reputation: 1

#include <iostream>
using namespace std;
class complex
{
private:
    int real;
    int img;

public:
    void set(int r, int i)
    {
        real = r;
        img = i;
    }
    complex(int r = 0, int i = 0)
    {
        real = r;
        img = i;
    }
    int getReal(){
        return real ;
    }
    int getImg(){
        return img ;
    }
    friend complex operator+(complex x, complex y);
    friend void Display(complex y);
    
};
/*freind functions of complex*/
complex operator+(complex x, complex y)
{
    complex z;
    z.real = x.getReal() + y.getReal();
    z.img = x.getImg() + y.getImg();
    return z;
}
void Display(complex y)
{

    cout << y.getReal()<< "+i" << y.getImg() << endl;
    return 0;
}
int main()
{
    complex c1, c2, c3;
    c1.set(78, 9);
    c2.set(68, 9);
    c3 = c1 + c2;
    c1.Display(c3);

    return 0;
}

Upvotes: -1

Related Questions