You are on page 1of 18
: Chapter 13 Operator Overloading 13.1 Overview! Allthe operators in €4-+ are designed to operate with the an arithmetic operator + can be used to but cannot be used to perform addition class Point to represe1 addition of tw basic data types only. For example, perform addition of integers, floats, doubles etc of user-defined objects. Let’s say if we create a ‘nt points in Cartesian coordinate system, we are not able to perform ‘© Point objects using operator + like we do it for Primitive types. Recall from Chapter 11 section 11.10 that addition of Point a function add () defined inside the class, P2 by making a call to add () as follows: P3=P1.add(P2) ; The function is invoked by P1 passing P2 is passed as an 'sstored in object P3, which gives the x and y coordinate addition of Point pbjects is performed using a member the arithmetic opeiptor + cannot be used to perform addition of user-defined objects. The basic principle of $perator overloading is to extend the capability of C++ operators in order to use them With user-defined types in the same Way and with the same syntax as with basic types. a fair expectation same way as they are If we overload oj objects as follows: P3=P1+P2 i Making use of opefator + to add Point objects makes the statement very easy to read and_ ‘ihatstand when compared tothe former statement, Opertee overloading is essentially used by the programmers ig cigate Programs with a friendly syntax. Clearly it is not 4 necessity, but it provides Sreat luxury to the programmers fo read and maintain the Program. Even wit operator, you can still perform addition of Point objects using the statement P3=P1,add (P2) ; however P3=P1+P2; is much programmer add (P2) ; argument, the result of addition values of the resultant point. The function ada (), merely because Performed with primitive types, erator + in class Point, we will be able to perform addition of Point ly when compared to P3=PL 700 + Comter Programming with C44 NOTES ‘When an operator is overloaded, it can take multiple forms and its behaviour will be dependent upon the context in which the operator is used. For example, if a and b are variables of type integer, the expression a+b will perform oper, *TYPE> operator ( = + ; Operator overloading allows the programmer to enhance the semantics-or even change them-of the operator when redefining its behaviour for user-defined types. But programmer can in no way attempt to change the syntax to be followed to use the operator. This means that ‘operator should be used with user-defined types with the same syntax as with basic types, evenif it is overloaded. In fact, this is the reason why you would want to overload any operator ‘Although, operator overloading technically allows you to drastically change the meaning / semantic of the operator for user-defined types, it is not recommended that you do so. For example, if we overload operator +, for using it with objects of class Point, then we may create the operator function as a member function of class Point as shown in Figure 13.2, ‘We should now be able to use operator + along with objects of class Point as shown, below: = + ; Let us assume that the function body of the operators is written by the programmer such that the operator function performs multiplication instead of actually performing ion, This means that the meaning or semantics of operator + is now changed to Oe en by the programmer, which is actually defined as addition by C++, S -» - 702 Computer Programming with Ces Operator to be overloaded class Point: te operators () 6 } function body hi Figure 13.2: Creating operator function as an inline member function of the class If P1, P2, and P3 are objects of class Point, we can use + with these objects because operator + is defined for class Point. P3 =P1+P2; However, the meaning of the above statement will depend on the actual operations that are performed inside the body of the operator function: If the operator+ function internally performs multiplication the statement P3 =P1+P2, it will then actually perform multiplication of Point objects instead of addition. This reflects that we have easily changed the meaning or semantic of operator-+ for objects of class Point, but the syntax of operator+ still remains unchanged. This action hampers the readability of the program badly anybody who views the statement P3=P1+P2 would get an impression that this is an addition at a first glance, but what actually happens in multiplication! Hence, it is strongly recommended not to change the semantics of an operator when overloading it The point we have just discussed is illustrated in the Figure 13.3. STEPS operacor can te esd with ojos of class Point Point because we have ( reloaded operator ° te oer fain oer a ae alah sing a operate ft overloaded operator+teargunents>) psgpite2: ( /roperator function internally So performs miltiplication*/ pets muito of ) sver2 Polat sje net of eon lage ie roming aston, Thi : J > meting of + toe came senate of he the bier ost operator’ ae changed Point 27 opera fucion Figure 13.3: Operator function changing the semantics of the operator» _Secaneee ven oo epee Suede ‘means that C++ always follows the ~ priority ‘of the operator that is actually overloaded, and it is immaterial of the at s defined by the programmer. Hence, even if the programmer has changed _ the semantic will still follo to mathemati priority ofade in the prograr while overloa The follow function: Arithmetic op Binary operators Unary operators Shorthand opera Logical operate Bitwise operate Relational oper Parenthesis: [J rato Dynamic memo: Others: Funct 13.3 Overlea As an example t operators ~ (whic ‘sign used to nega will use ~ and - us create a class 1 input () and out, print their values, Data. Given that different operator f is to find one’s com Data res; res.a= rea.b=-b; return res; ‘The calculated one’s res by the operator function. It is clear th operation and hence Operator Overloading + 703 the semantics of the operator+ to internally perform multiplication of points, C++ will still follow priority, associativity, and grammatical rules of addition. This may lead to mathematically incorrect results because multiplication can now be performed with a priority of addition, Operator overloading should not be misused to create such confusions in the program. | emphasize th ics of the operator should not be changed while overloading an operator, altl “++ allows you to do so. The following is the list of C++ operators which can be overloaded using an operator functior Arithmetic operators: Binary operators: + , Unary operators: ++, Shorthand operators: +=, -=, Logical operators: &&, ||, ! Bitwise operators: &, |, ~, *, >>, <<, bos Relational operators: >, >=, <, <=, ==, Parenthesis: [], () Operat with pointers: ->, ->*, * (indirection) ,& Dynamic memory allocation: new, delete Others: Function call operator, type cast operator, comma operator 13.3 Overloading One's Complement ~ and Minus - Operators: An Example As an example to understand overloading of unary operators, let us overload unary operators ~ (which finds one’s complement of a number) and — (which is a unary minus sign used to negate a number). This means that we intend to create a C++ program that will use ~ and ~ operators with objects of class. To understand this overloading, let us create a class Data with two integer members a and b and two member functions input () and output () for accepting the member variables as input from the user and to print their values, respectively. We will learn to use operators ~ and - with objects of class Data. Given that there are two operators which we need to overload, we must create two different operator functions in class Data. The job of the operator function operator~() is to find one’s complement of the members a and b using the following statements: Data res; return res; The calculated one's complement of members a and b i stored in a neal cblect Ramet res by the operator function, which is then returned to the caller we function. Itis clear that the function returns another object of class Data as a result of its operation and hence the return type of the funetion should be Data.

You might also like