3

Normally when you declare a method within a class declaration, and define it outside, you need to specify its scope.

Since I've read that operators are pretty much regular methods, I find it hard to understand the following behavior:

class A
{
public:
    A(int x)
    { this->x = x;}
    int foo();
    friend const A operator+ (const A& left,const int right);

private:
    int x;
};

const A operator+ (const A& left,const int right) //can't be A::operator+
{
    return A(left.x + right);
}

int A::foo()  // A:: is needed here
{
    return 5;
}

int main(int argc, char **argv) {
    A a(1);
    a = a + 4;
    a.operator =(a+5);
    a.foo();
}

Why don't we need to specify which "operator+" we're defining\overloading? Is it inferred from the operands?

Shinnyx
  • 2,144
  • 2
  • 14
  • 21
Paz
  • 737
  • 7
  • 22
  • *"Is it inferred from the operands?"* Yes (simplifying). operators are defined like regular functions or member functions, but the way they're found is a bit tricky and more complex than lookup for ordinary functions / member functions. – dyp Apr 03 '14 at 20:03
  • Related: http://stackoverflow.com/q/4603886/420683 and http://stackoverflow.com/q/19122575/420683 – dyp Apr 03 '14 at 20:05
  • @dyp Note that no namespaces are involved in the question. When I read the title, I was thinking "Koenig lookup", too, but that doesn't seem to be what the question is about at all. – sepp2k Apr 03 '14 at 20:08
  • @sepp2k The global namespace is associated with `class A`. However, this operator can also be found via unqualified lookup. I wasn't referring to ADL in my comment, but to name lookup for operators in general. – dyp Apr 03 '14 at 20:09

3 Answers3

10

Because operator+ is a free function, which is completely unrelated to the A class. It just so happens that one of its arguments is of class A.

This means that it is not the same as A::operator+ which would be defined as:

class A {
public:
    const A operator+(const int);
};

In your code sample you are defining a friend function to the class. So the free function can now access the private and protected part of the class. If you wouldn't define it (operator+) friend would only be able to access public members of A. That's why you are making it friend.

Shoe
  • 74,840
  • 36
  • 166
  • 272
1

This is because the operator+ in this case is not a member of class A, but a friendly function.

INait
  • 181
  • 6
0

In your case, operator+ is not a member of class A. This is usually the correct way to define binary operators so that the operator can be used with a literal on the left hand side.

However, most operators are defined as normal class members within the class scope. EG,

A& A::operator=(A rhs)
{
    swap(rhs);
    return *this;
}

Here's a more complete answer: Operator overloading

Community
  • 1
  • 1
user823981
  • 102
  • 6