Chapter 12: Overloading Operators in C


OVERVIEW

You have already seen numerous examples of overloaded operators in C++ and Java. For example, when you say in Java

      String str = "hello" + "there"; 

or in C++

      string str = "hello" + "there"; 

you are using the overloaded definition of the ‘+' operator. Generically, the operator ‘+' is intended for adding numbers, but here we are using it to join together two strings. We are able to do so because the class definition for the string type usually includes an appropriate overload definition for the operator ‘+' that makes it possible to join together two strings.

While you will find overloaded operators in both C++ and Java, you are not allowed to create your own operator overloadings in Java.

Here is a list, reproduced from [54], of key points to remember about operator overloading in C++.

  • When an operator is overloaded in C++, at least one of its operands must be of class type or enumeration type.

  • At least one of the operands in an operator overload definition must not be a built-in type.

  • The predefined precedence of an operator cannot be altered by an overload definition.

  • An overload definition also cannot alter the predefined arity of an operator, meaning that an operator that is designated to be only unary (for example, the logical NOT operator ‘!') cannot be turned into a binary operator by overloading. For operators that can be used for both unary and binary operations (these being the four operators ‘+' ‘' ‘*' and ‘&'), both arities can be overloaded.

  • Arguments can be passed to the parameters in the overload definitions either by value or by reference, but not by pointer.

  • Default arguments for overloaded operators are illegal, except for the operator ‘()'.

  • Finally, the following operators cannot be overloaded:

          :: .+ . ?: 




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net