I could use some help understanding the following in C++, particularly the difference between an operator and a function:
What is operator?
An operator is generally an operation performed on a variable given some form of punctuation. For example, the default behavior of operator+
between two integers is to add them.
What is function?
A function is a subroutine -- a reuseable block of code.
What is the difference between them?
Nothing, as far as user code is concerned, except for syntax. Note that if you override operator||
, operator&&
, or (to a lesser extent) operator,
, you change the semantics of the built in operator semantics. In the case of &&
and ||
, you make the operation which is normally short circuiting into an operation which is not. In the case of the comma, you would need to ensure that you evaluate the arguments left to right, as the comma operator normally behaves in this way.
Is user-defined operator+() a function or operator?
Neither. It is a user defined operator overload. A function name cannot start with the keyword operator
, and an operator is simply the actual punctuation mark used to invoke the operator overload, i.e. +
or -
. EDIT: Note that while technically speaking it is not a function, it does have the semantics of a function call, as demonstrated in @Martin York's excellent answer.
Can operator operate on operands at compile-time? Do they always operate at compile time? (like sizeof() in C++)
No, sizeof
cannot be overloaded. If you want some form of compile time operation done, you need to use something like template metaprogramming. Note that if the compiler is able to do the calculation at compile time it may elide the call into your overloaded operator, of course.