Johnny Pauling
Johnny Pauling

Reputation: 13437

Operator override - when to use friend?

I'm wondering why the () operator override can't be "friend" (and so it needs a "this" additional parameter) while the + operator needs to be friend like in the following example:

class fnobj
{
    int operator()(int i);
    friend int operator+(fnobj& e);
};

int fnobj::operator()(int i)
{

}

int operator+(fnobj& e)
{

}

I understood that the + operator needs to be friend to avoid the "additional" extra this parameter, but why is that the operator() doesn't need it?

Upvotes: 2

Views: 535

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63946

You have overloaded the unary plus operator. And you probably didn't want to do that. It does not add two objects, it describes how to interpret a single object when a + appears before it, the same as int x = +10 would be interpreted. (It's interpreted the same as int x = 10)

For the addition operator, it is not correct that "the + operator needs to be friend".

Here are two ways to add two fnobj objects:

int operator+(fnobj& e);
friend int operator+(fnobj& left, fnobj& right);

In the first form, this is presumed to be the object to the left of the +. So both forms effectively take two parameters.

So to answer your question, instead of thinking that "operator() doesn't need friend", consider it as "operator() requires this" Or better still, "Treating an object as a function requires an object".

Upvotes: 4

filmor
filmor

Reputation: 32298

You didn't understand this correctly (and aren't using it correctly as well).

There are two ways in C++ to define a binary operator for a class, either as a member function

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

or as a free function

class A {};

int operator+ (A const& lhs, A const& rhs);

What you are currently mixing up is that you can declare and define this free function in the class scope as friend, which will allow the function to use private members of the class (which is not allowed in general for free functions).

Upvotes: 2

Related Questions