Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top