Operator Overloading
suggest changeIntroduction
In C++, it is possible to define operators such as \+ and -> for user-defined types. For example, the <string> header defines a \+ operator to concatenate strings. This is done by defining an operator function using the operator keyword.
Remarks
The operators for built-in types cannot be changed, operators can only be overloaded for user-defined types. That is, at least one of the operands has to be of a user-defined type.
The following operators cannot be overloaded:
- The member access or “dot” operator
. - The pointer to member access operator
.* - The scope resolution operator,
:: - The ternary conditional operator,
?: dynamic_cast,static_cast,reinterpret_cast,const_cast,typeid,sizeof,alignof, andnoexcept- The preprocessing directives,
\#and##, which are executed before any type information is available.
There are some operators that you should not (99.98% of the time) overload:
&&and||(prefer, instead, to use implicit conversion tobool),- The address-of operator (unary
&)
Why? Because they overload operators that another programmer might never expect, resulting in different behavior than anticipated.
For example, user-defined overloads of && and || lose short-circuit evaluation and lose the sequencing of the built-in operators. The same sequencing issue applies to overloads of the comma operator. Built-in &&, ||, and , sequence their operands. C++17 states that sequencing more precisely.