Operator Overloading: Some Rules and Convention

Written by Raza on. Posted in C++

A week ago, we saw how to overload an assignment operator in object oriented paradigm. As a whole, operator overloading is an important and challenging task. Bjarne Stroustrup, the author and designer of C++ took considerable pain to ensure that user defined types become as close to the built in types as possible. Operator overloading is an offshoot of this. It saves time, energy, resources and many potential dangers to the program. There are certain rules and conventions while overloading operators. Some of them are described in this article.

Rules of Operator Overloading:

  1. Only those operators could be overloaded which are supported by the language. You cannot create any of your own symbols as operators. E.g. you cannot overload ‘   ‘  or ‘    ’operator.
  2. For the existing operators, overloading is allowed only in the format which language supports. E.g. you can overload ‘  +  ’ and
    ‘    ’ but cannot create this thing. ‘  +-  ’. These operators are not supported in this combined way.
  3. All the existing operators in C++ could be overloaded except six operators. These are ‘  ?:  ’, ‘  sizeof  ’,  ‘  .*  ’, ‘  ::  ’ , ‘  .  ’ and
    ‘  typeid  ’ operators. Why? Look them up yourself!
  4. You cannot change the precedence or associativity level of the operators by overloading them. That feature still resides with the language standards.
  5. There are certain operators whose overloaded functions have some limitations. One is assignment operator. It must be declared as a member function of the class. On the other hand, insertion (<<) and extraction (>>) operators should always be declared as non-member functions of the class. Remember that they should be declared non-member functions only when associated with istream and ostream; for input and output to objects.

Conventions of Operator Overloading:

  1. By overloading an operator, you can actually perform the functionality of choice by it. But it is better to use it as it is normally used for built in types. By that, I mean that always perform addition with ‘  +  ’ operator rather than subtraction. It is better to understand and saves from many complications which may arise as well.
  2. If there is even a single pointer as data member in your class, it is very good to always write at least the assignment operator in the very beginning. This proves really helpful during the whole program.
  3. Try to build them as much close to the built in operators so that they perform the same way. Take special care of the nested use of operators and change the return type of the functions accordingly. E.g. cater for such operations. a = b = c and x + y + z.

There are many others as well especially the rules but I’ve left them for now. See you next time.

Tags: , ,