What Are the Basic Rules and Idioms For Operator Overloading

C++ operators overload, rules for spaces in expression

Other than in character and string literals, the only place in C++ code where whitespace is significant is to separate tokens that would be (or could be) otherwise merged.

In your case, there is a clear separation between the three tokens, operator, + and (, so the added space characters make no difference whatsoever to how the compiler will interpret the declaration.

However, something like Toperator+(T t1, T t2) is invalid, because the T and the operator will now be treated as a single (identifier) token.

As for which one is "best" – that's really a matter of taste and opinion, although cppreference generally uses the "no space" option for overload declarations.

How to add rhs value to class in C++ (operator overloading) [duplicate]

Like this, calling your existing matrix * scalar function with the arguments reversed:

inline matrix operator*(int scalar, const matrix& mat) {
return mat * scalar;

The above is a free function, to be declared in whatever namespace matrix is in, not inside the class.

C++ Operator Overloading '+' [duplicate]

Your operator+ function should have the following signature if you want to use a claa member operator+:

Money operator+( const Money& ) const;

Or you may also define it as not member of the class:

Money operator+( const Money&, const Money& );

Related Topics

Leave a reply