I'm trying to understand operators in C++ more carefully.
I know that operators in C++ are basically just functions. What I don't get is, what does the function look like?
Take for example:
int x = 1;
int y = 2;
int z = x + y;
How does the last line translate? Is it:
1. int z = operator+(x,y);
or
2. int z = x.operator+(y);
?
When I tried both of them, the compiler errors. Am I calling them wrong or are operators in C++ not allowed to be called directly?
As has been mentioned in commentary and in other answers, by there is no
operator+
for fundamental types. For classes, the answer to which ofoperator+(x,y)
versusx.operator+(y)
is correct is "it depends". Particularly, it depends on howoperator+
was defined. If it was defined as an member function then you need to usex.operator+(y)
. If it was defined as a global function then you need to useoperator+(x,y)
.When the compiler confronts the statement
z=x+y;
your compiler is smart enough to look for the appropriate form. You shouldn't be expecting one or the other. You should be usingx+y
.Using C++ standardese, the function call syntax (
operator+(x, y)
orx.operator+(y)
) works only for operator functions:And operator functions require at least one parameter that is a class type or an enumeration type:
That implies that an operator function
operator+()
that only takesint
s cannot exist per 13.5/6. And you obviously can't use the function call syntax on an operator function that can't exist.For native types, the operators aren't functions. Only overloaded operators are functions. Built-in operators are built-in - they don't have "functions", they usually just compile down to one or two assembly instructions that it would be insane to call as a function.
So neither
operator+(x, y)
norx.operator+(y)
is correct. I supposex.operator+(y)
is less correct because non-struct
types can't have members, but I doubt that helps much.You can't overload binary operators when both arguments are built in types. However for your own objects this is how you can create them.
Operator overloads only apply to objects and structs, not to fundamental types (such as int or float). If you had an object class like:
then you can indeed call
myA.operator+(anotherA)
and that will be equivalent tomyA + anotherA
.For basic types like
int
,float
,double
; the operators are already overloaded/pre-defined, so nothing special can be done for that. And,is the only way to express/call it.
For interpretation purpose, actually both the statements,
are true (had it been overloadable).