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?
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 asint x = +10would be interpreted. (It’s interpreted the same asint x = 10)For the addition operator, it is not correct that “the + operator needs to be friend”.
Here are two ways to add two
fnobjobjects:In the first form,
thisis 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() requiresthis” Or better still, “Treating an object as a function requires an object”.