Murali VP
Murali VP

Reputation: 6417

operator overloading in C++

Besides 'new', 'delete', '<<' & '>>' operators, what other operators can be overloaded in C++ outside of a class context?

Upvotes: 3

Views: 506

Answers (2)

Faisal Vali
Faisal Vali

Reputation: 33673

The following operators (delimitted by space) can be overloaded as non-member functions:

new delete new[] delete[] + - * / % ˆ & | ˜ ! < > += -= *= /= %= ˆ=  
&= |= << >> >>= <<= == != <= >= && || ++ -- , ->* 

The following have to be non-static member functions:

-> () [] = 

The following can not be overloaded:

. .* :: ?: # ##

conversion operators also have to be member functions.

And just because it has a '=' in it does not mean it cannot be overloaded as a non-member operator. The following is well-formed:

struct A { };
A operator +=(A,A) { return A(); }
A a = A()+=A();

And the prefix and postfix increment and decrement operators can indeed be defined as non-members:

13.5.7 The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.
The prefix and postfix decrement operators -- are handled analogously

Clause 13.5 in the Standard covers this.

Hope this helps.

Upvotes: 4

bbg
bbg

Reputation: 3072

Operators that can be overloaded (comma used as delimiter):

+, -, *, /, %, ^, &, |, ~, !, =, <, >, +=, -=, *=, /=, %=, ^=, &=, |=, >>=, <<=, !=, <=, >=, &&, ||, ++, --, ->* , (i.e., comma operator), ->, [], (), new[], delete[]

Operators that can not be overloaded: ., .*, ::, ?:

Operators where overloading function must be declared as a class method: (), [], ->, any assignment operator (as the commenters noted)

Upvotes: 4

Related Questions