2

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?

2 Answers 2

4

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".

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, and the () operator is called on a single object so must necessarily be a member function, is that correct?
@JohnnyPauling Correct. I've edited my answer to illuminate that.
@JohnnyPauling if you do some searching (or asking here) you can learn how the friend form of addition is preferred, for one particular reason.
Why is that Drew? I'm interested
@JohnnyPauling Hit the ask question button. Don't assume that I can give you the best answer. I don't. :)
|
2

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.