Monday, October 31, 2011

Operator Overloading in C++

Just wrap-up the notes for operator overloading in C++.

  1. Almost all operators can be overloaded in user-defined classes, except the following four.
    .   .*   ::   ?:
  2. Some operator overloading can be defined as class member function only.
    ()   []   ->   "any assignment operators"   "type conversion"
    Question: how about ->*?

  3. In some cases, global functions are needed to implement operator overloads.
    1. When using stream operator on a user-defined class, it may be impossible to overload the cout's member operator functions for a general programmer. In this case, global functions is needed.
    2. When defining some operations requiring commutability, the global function approach is necessary, since class member functions always take the object itself as the first implicit argument.

  4. Prefix increment and decrement overloads are exactly the same as any other unary operators. For postfix increment and decrement, the compiler will generate a function call operator++ with one int argument 0 (or besides the class object parameter in global functions).

  5. Type casting operations are possible using operator overloading. For example,
    A::operator int() const;
    A::operator B() const;   // class B should be defined/declared before class A
    Note that the return type may not be specified on a type casting function.

1 comment: