In C++, binary operators can either be overriden with one or two operators, when the LHS is the class being declared. If declared with two parameters in must be a non-member function. Vis in this code, the two declarations are identical.
class MyClass
{
public:
MyClass operator+(const MyClass&);
}
MyClass operator+(const MyClass&, const MyClass&);
Is there a reason the latter can not be done as a static member function? Like this
class MyClass
{
public:
static MyClass operator+(const MyClass&, const MyClass&);
}
It would make writing the stream in/out operators easier (I am aware you can use friend
to declare the operator)
An operator which contains two operands to perform a mathematical operation is called the Binary Operator Overloading. It is a polymorphic compile technique where a single operator can perform various functionalities by taking two operands from the programmer or user.
Operator overloading of non-member function or friend function. A non-member function does not have access to the private data of that class. This means that an operator overloading function must be made a friend function if it requires access to the private members of the class.
The function call operator or operator template is declared static if the lambda-expression has no lambda-capture, otherwise it is non-static. If it is a non-static member function, it is declared const ([class. mfct.
Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.
The logic is that a+b
can be interpreted as operator+(a,b)
or as a.operator+(b)
, each of which looks plausible if you squint. The former can’t find any member functions; the latter could find static ones, but would uselessly pass only b
to them. A static one could be called properly via an interpretation as a.operator+(a,b)
, but that would attempt to pass an extra argument to any non-static member (possibly turning a unary -
into a binary one, for instance). It would also defeat the feature of allowing conversions on the first argument, since its (original) type would restrict the candidates via name lookup.
There is one case where operator+(a,b)
could find a member function—when the operator itself appeared in a class (member function). The unqualified lookup for such a name specially ignores class members because they (non-static as they are) would have the wrong arity and (very often) would be for the wrong type (shadowing all non-member functions for the same operator!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With