Add to Technorati Favorites
Google

Operator Overloading

  • Operator overloading feature makes C++ an extensible language
  • You can overload the built-in operators of C++ for user-defined data-types or combination of user-defined and built-in types. For e.g. using strcat(str1,str2) is not that intuitive as res = str1+str2 i.e. overloaded '+' for string concatenation.
  • However, you can overload most of the operators but not all.
  • By overloading an operator, you cannot change its semantics, associativity, and precedence. For e.g., you cannot overload a binary operator to become unary.
  • Syntax for operator overloading
Keyword 'operator' is used with following syntax(es):

//Binary Operator Overloading as member function
returnDataType className::operator oprSymbol(class a);

//Unary Operator Overloading as member function
returnDataType className::operator oprSymbol();

//Binary Operator Overloading as friend function
friend returnDataType oprSymbol(class a, class b);

//Unary Operator Overloading as friend function
friend returnDataType oprSymbol(class a);

Points to Ponder

  • If a binary operator is overloaded as a member function then function takes 1 parameter and if as a friend function then 2 parameters
  • If a unary operator is overloaded as a member function then function takes no parameter and if as a friend function then 1 parameter
  • In operator overloading as a member function, one parameter is provided by the invoking class.

Which operators cannot be overloaded? Why the first parameter should be an object and not a built-in type? How to overloaded postfix and prefix versions of increment and decrement operators? To know answers to these and many other such issues in operator overloading, you may request a presentation file (ppt) on operator overloading by e-mailing me at:

zainvi.sf@gmail.com zainvi[dot]sf[at]gmail[dot]com

No comments: