Why ambiguity only for overloaded operators and not for functions with "same" name but different scope?

Viewed 76

Consider the example:

class Gfg { 
public: 
    void printHello() 
    { 
        cout << "hello gfg-class specific" << endl; 
    } 
}; 
  
void printHello() 
{ 
    cout << "hello gfg-global" << endl; 
} 
int main() 
{ 
    Gfg a; 
    a.printHello(); 
    printHello(); 
} 

This code works fine.

But see other example for operator overloading, it will not compile.

class Gfg { 
public: 
    Gfg operator+(Gfg& a) 
    { 
        cout << "class specific + operator" << endl; 
        return Gfg(); // Just return some temporary object 
    } 
}; 

Gfg operator+(Gfg& a, Gfg& b) 
{ 
    cout << "global + operator called" << endl; 
    return Gfg(); // Just return some temporary object 
} 

int main() 
{ 
    Gfg a, b; 
    Gfg c = a + b; 
} 

I thought in both cases name mangling(decoration) will make both name as unique name and member function will be given preference and hence member version of operator+ should be called, which doesn't happen. why?

1 Answers

The ambiguity resides in the use of c = a+b;. It is ambiguous because we do not know if we call the operator in the class (with one parameter) or the one outside the class (with two parameters). Using the call with the operator keyword clarifies a little bit: c=a.operator+(b) or c =operator+(a,b).

Thus the ambiguity.

I modified your code like this:

#include <iostream>

using namespace std;
class Gfg {
public:
    Gfg operator+(const Gfg& a)
    {
        cout << "class specific + operator" << endl;
        return Gfg(); // Just return some temporary object
    }
};

Gfg operator+(const Gfg& a, const Gfg& b)
{
    cout << "global + operator called" << endl;
    return Gfg(); // Just return some temporary object
}


int main()
{
    Gfg a, b,c,d;
    c = operator+(a,b); // equivalent to c = a+b
    c = a.operator+(b); // also equivalent to c=a+b

}

The code compiles and the output is the following :

global + operator called
class specific + operator
Related