0% found this document useful (0 votes)
5 views

Operator overloading and type conversion

Unit 6 covers operator overloading and type conversion in object-oriented programming, explaining how to define and implement operator functions for both unary and binary operators. It also discusses the rules for overloading operators and the various typecasting methods available in C++. The unit emphasizes the importance of understanding these concepts to create intuitive and efficient code.

Uploaded by

Heureuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
5 views

Operator overloading and type conversion

Unit 6 covers operator overloading and type conversion in object-oriented programming, explaining how to define and implement operator functions for both unary and binary operators. It also discusses the rules for overloading operators and the various typecasting methods available in C++. The unit emphasizes the importance of understanding these concepts to create intuitive and efficient code.

Uploaded by

Heureuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
Unit 6: Operator Overloading and Type Conversion Structure 61 Introduction 62 Defining Operator Overloading 63 Overloading Unary Operators 64 Overloading Binary Operators 65 Rules for overloading operators 66 Typecasting 67 Summary 68 Check Your Progress 69 Questions and Exercises 610 Key Terms 611 Further Readings Objectives After studying this unt, you should be able to ‘© Understand the Operator overloading. ‘© Learn about data conversion 6.1 Introduction Operator overloading is one of the most exciting features of object onented programming. It can transform complex, ebscure program listings into intuitively obvious ‘ones, 6.2 Defining Operator Overloading To define an additional task to an operator we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function, called operator function, which describes the task. The general form of an operator function is, where returntype is the type of value retumed by the specified operation and ap is the operator being overioaded. The op is preceded by the keyword operator. operator opis the function name. Operator functions must be either member functions (non-static) or friend functions. A basic difference between them is that a friend function will have only one argument for unary operators and two for binary operators, while a member function has no arguments for unary operators and only one for binary operators. This is, because the object used fo invoke the member function is r_sed implicitly and therefore Notes 126 Notes (Object Oriented Programming with O-+ {s available for the member function. This is not the case with friend functions, Arguments may be passed either by value or by reference Operator functions are declared in the class using prototypes as follows vector operator + (vecton: ‘wecte_ addition vector operator - () Munary minus friend vector operator + (vector, vector): Nector adition friond vector operator- (vector; ‘fanary minus vector operator - (vector & a) ‘subtraction int operator == (vector: !Neomparison friend int operator == (vector, vector) {Yeomparison vector is a data type of class and may represent both magnitude and direction (as in physies and engineering) or a series of points called elements (as in mathematics) The process of overloading involves the following steps: 1. First, create a class that defines the data type that is to be used in the overloading operation. 2. Declare the operator function operator op ( ) in the public part of the class. It may be either a member function or a friend function 3. Define the operator function to implement the required operations 6.3 Overloading Unary Operators Lets start off by overloading @ unary operator. Unary operators act on only one operand. Examples of unary operators are the increment and decrement operators ++ and, and the unary minus, asin 3 Lot's consider a program showing how the unary minus operator's overloaded, 2 include publics void getdata (int aly i void display (void): Operator Overicading and Typs Conversion void unaryl :: operator -() display (void) ) J) batining cpeveror -() unaryl us data (45, cea? u. display(): a. display () The program produces the following output a: 45 -e0 € ur -45 60 -60 Note that the function operator -() takes no arguments. Then when does this operator function do? It changes the sign of data members of the object u. Since this function is a member function of the same class, it can directly access the members of the object which activated it Remember, a statement lke w2 will not work because, the function operator -() does not return any value. It can work if the function is modified to retum an object. itis possible to overload a unary minus operator using a friend function as follows: ut Friend void operator -(unary & u): x -(unary lex (else complex operator + (6 void display [vetay; complex complex Operator Overcading and Typs Conversion cout KEM EE" Key KERN /) invokes /) invokes /) invokes /) invokes asa We should note the following features of the function operator +(): 1. Itreceives only one complex type argument explicitly. 2. Itreturns @ complex type value 3. tis @ member function of complex ‘The function is expected to add two complex values and return a complex value as the result but receives only one value as argument. Where doas the other value come from? Now let us look at the statement that invokes this function 3 1 +02 (/ invokes operator + () function We know that a member function can be invoked only by an object of the same class. Here, the object C1 takes the responsibilty of invoking the function and C2 plays to the function. The above invocation statement is equivalent to ©: C1. operator +(C2) ‘v usual function Ji call syntax ‘Therefore, in the operator +() function, the data members of C1 are accessed directly and the data members of C2 (that is passed as an argument) are accessed using the dot operator. Thus, both the objects are avallable for the function 6.5 Rules for overloading operators There are some restrictions and limitation in averloading the operators. Some of them ae listed below 1. Only existing operators ean be overloaded 2. The overicaded operator must have at least one operand which must be user defined type. 129 Notes 130 Notes (Object Oriented Programming with O-+ 2. You cannot change the basic meaning of an operator. 4. Overloaded operators must follow the syntax rules of the original operators. “Inend’ functions must not be use to overload certain operators. However, member function can be used to overload them. © Unary operators, overloaded by means of @ member function, take no explicit arguments and return no explicit values. 7. Binary operators overloaded through a member function take one explicit arqument and those which are overloaded through a friend function take two explicit arguments. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class. Binary antnmetic operators such as +." and / must explicitly retum a value. They must not attempt to change their own arguments. 6.6 Typecasting Casts are used to convert the type of an object, expression, function arguments, oF Tetum value to that of another type. Some conversions are performed automatically by the compiler that is called implicit conversions. The standard C++ conversions and user-defined conversions are performed implicitly by the compiler where needed. Conversions which are explcily specified by the programmer and are called explicit conversions ‘The C+ craft standard includes the folowing four costing operators statie-cast const-cast dynamic-cast, and reinterpert-cast Standard conversions are used for integral promotions (e.g., float to double), floating. integral conversions (2.9.. int to float), floating point conversions (@.9. float to double), arithmetic conversions (e.g., converting operands to the type of the widest operand before evaluation), pointer conversions (e.9., derived class pointer to base Class pointer), reference conversions (e.g, derived class reference to base class reference], and pointer-to.member conversions. ‘You can provide a user-defined conversion from a class X to a class Y by providing ‘a constructor for Y that takes an X as an argument: ‘Yiconst X& x) or by providing a class Y with a conversion operator ‘operator X() When @ type is needed for an expression that cannot be obtained through an implicit conversion or when more than one standard conversion creates an ambiguous situation, the programmer must explicitly specify that target type of the conversion. C++ Introduces Four New Casting Operators 1. Static~cast, to convert one type to another type 2. Const-cast, to cost away the "const-ness’ or "volatie—ness” of a type. 3. dynamic—cast, for safe navigation of an inheritance hierarchy, 4. reinterpret-cast, to perform type conversions on un-related types All of the casting operators have the same syntax For example. to perform a static- cost of Pir toa Type T we write Operator Overcading and Typs Conversion 2 t = static~cost (ptr) ‘The Static-cast Operator ‘The Static-cast operator takes the form Static-cost (enpr) to convert the expression expr to type T. Such conversions rely on static (compile-time) type information, Internally, static-costs are used by the compiler to perform implicit type conversions such as the standard conversions are user-defined conversions. ‘The down cost of a base class pointer x to a derived class pointer y can be statically only i the conversion is unambiguous and x is not a virtual base class. Consider this class hierarchy, ss Bank point void £(Bank This is @ down cost. The statie-cost operator allows you to perform safe down casts {for non polymorphic classes. One of the more common uses of this type of casting Is to perform arthmetic conversions, such as from int to double. For example, to avoid the truncation in the tollowing computation A static-cost may also be used to convert an integral type to an enumeration Consider: 131 Notes 132 Notes (Object Oriented Programming with O-+ The Const-cast Operator The const-cast operator takes the form ) Consider a function, f, which takes a non-const argument, double f(doukle s 4)+ However, we wish to call f from another function g: voidg (const double « d) val = £(a); Since d is const and should not be modified, the compiler will complain because f may potentially modify ts value. To gat around this dilemma, we can use a const-cast ea) val = f(cons oec (4))+ Another scenario where const-cost is useful is inside const functions. For example, consider suppose that, f(), which is declared to be const, must modify-count whenever itis called: void 8: Operator Overcading and Typs Conversion The compiler will not allow-count to be changed because the function is const. It tums out that the type of the intemal this pointer helps the compiler perform this check Every non-static member function of a class C has this pointer. For non-const member functions of class C, this has type This means that this is a constant pointer. In other words, you cannot change what the pointer this points to, afterall, that would be disastrous We can, however, use const-cost to cost away the "const-ness” of this ‘The Dynamic-cast Operator ‘The dynamic-cost operator takes the form dynamic-cost (expr) and can be used only for pointer or reference types to navigate a class hierarchy. This ‘operator is actually part of C++'s run time type information, or RTT, sub-system All of the derived-to-base conversions are performed using the static (compile time) type information. These conversions may, therefore, be performed on both, non polymorphic and polymorphic types. These conversions will produce the same result if they are converted using a static-cost Let's look at the power of run-time type conversion by revisiting the bank account higrarchy introduced above with static-cost. Recall that when acct. does not actually point to @ savings Acct object, the result of the static-cost is undefined. Since Bank Acct. has at least one virlual function, ts a polymorphic class. We can use a dynamic cost instead to check that the cost was successful: void f(eank Let's expand our bank account hierarchy fo include a few more types of accounts, such as a checking account and a money market account. Let's suppose we also want to extend the functionality so that we can credit the interest for all savings and money market accounts in our data base. Suppose further that Bank Acct. is part of a vendor 133 Notes 134 Notes (Object Oriented Programmimg with C++ library, we are not able to add new members functions to Bank Acct. since we do not have the source code. Clearly, the best way to incorporate the needed functionality would be to add a virtual tuncton, credit interest() to the base class, Bank Acct. But since we are not able ‘0 modify Bank Acct, we are unable to do this. Instead, we can employ a dynamic-cost, to help us We add the method credit interest ) to both Savings Acct. and MM Acct. classes. The resulting class hierarchy looks lke ings A public: void comp) mat void comput void De sa doves: ma = dynam: Operator Overicading and Typs Conversion A dynamic-cast will return a null pointer if the cost is not successful, so only if the pointer is of type Savings Acct” or MM Acct” is interest credited. Dynamic-cast allows Yyou 10 perform safe type conversions and lets your programs take appropriate actions ‘when such casts fail When a pointer is converted to a void", the resulting object points to the most derived object in the class hierarchy. This ‘enables the object to be seen as raw memory. Meyers demonstrates how a cost to void* can be used to determine if a particular object is on the heap ‘The reinterpret-cast Operator ‘The reinterpret-cost operator takes the form reinterpret.cost (expr) and is used to perform conversions between two unrelated types. The result of the conversion is usually implementation dependant and, therefore, not likely to be portable. You should use this type of cost only when absolutely necessary. A reinterpret-cast can also be used to convert a pointer to an integral type. You typecasting is making @ variable of one type, such as an int, act like another type, & char, for one single application. To type cast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char) a will make ‘a’ function as a cher. ‘One use for typecesting for is when you want to use the ASC! characters For example, what if you want to create your own chart of all 256 ASCi/ characters. To do this, you will need to use to type cast to allow you to print out the integer as its character equivalent #include 135 Notes 136 Notes ‘Object Oriented Programming wit C+ / The ASC// character set is goon 0 coutsenc<". "<< (char) acc" ") These new operators are intended to remove some of the holes in the (type system introduced by the old c-styie costs, 6.7 Summary Operator overloading is one of the most exciting features of object oriented programming. Itcan transform complex, obscure program listings into intuitively obvious ones. To define an additional task to an operator we must specify what it means in relation to the class to which the operator is applied. Operator functions must be either member functions (non-static) or fend functions, A basic difference between them is that a fiend function will have only one argument for unary operators and two for binary operators, while a member function has no arguments for unary operators and only one for binary operators. Typecasts are used to convert the type of an object, expression, function arguments, or return value to that of another type. Some conversions are performed automatically by the compiler that is called implicit conversions, The standard C++ conversions and user-defined conversions are performed implicitly by the compiler where needed. Conversions which are explicitly specified by the programmer and are called explicit conversions, 6.8 Check Your Progress Multiple Choice Questions 1. Pick the other name of operator function. fa) function overloading b)_ operator overloading c)_ member overloading d) None of the mentioned 2. Which of the following operators can't be overloaded? a) b+ o a0 3. How to declare operator function? Operator Overicading and Typs Conversion a) operator operator sign '). operator ©). operator sign d)_ None of the mentioned 4. What is the output of this program? #include using namespace std, class sample { public: intx, ¥; sample() sample(int, int) sample operator ~ (sample); hi sample sample (int a, int b) sample sample-operator« (sample param) ( sample temp tempx =x + param.x; tomp y=y + paramy, return (temp), , intmain ( sample a (4,1) sample b (32) sample c c=arb, cout < using namespace std: 137 Notes 138 Notes (Object Oriented Programmimg with C+ class Box { double length double breadth: double height: public: double getVoluma(void) { return length * breadth * height; } void setLength( double len ) { length = len) i void setBreadth( double bre ) { breadth = bre } Void setHeight( double hei ) c height = het ) Box operator+(const BoxA. b) c Box box, box length = thislength + blangth; box breath = this.>breadth + b.breadth box height = this>height + b.height; return box ) % intmain() r Box Boxt Box Box2 Box Box’: double volume = 0.0, Box’ setLengthi6.0) Boxt.setBreadthv6 0) Boxt sotHight(5 0) Box? setlength( 12.0), Box2 setBreadtn(13.0); Box settterght(10.0) Operator Overcading and Typs Conversion volume = Boxt getVolume() cout << "Volume of Boxt :" << volume < using namespace std, class Integer { inti, public: Integer(int i): Wi) const Integer operator+ (const Integer& rv) const { cout << "operator#” << endl return Intoger(t+ rv.), } Integer& operator+=(const Integer’ rv) t cout << “operator i < using namespace std class myclass c public: inti, myclass “operator->() {retum this) ‘ int main) £ myclass ob ob--i = 10, cout << ob i <<" << obi retun 0 } a) 1010 by 111 ©) error d) runtime error 8. Which of the following statements is NOT valid about operator overloading? a) Only existing operators can be overloaded ) Overicaded operator must have at least one operand of its class type. c) The overloaded operators follow the syntax rules of the original operator @) None of the mentioned 8 Operator overioading is a)__making c++ operator works with objects ) giving new meaning to existing operator ¢)_making new operator @) bothaad Notes Operator Overicading and Typs Conversion 10. What is the output of this program? #include using namespace std: ostream & operator=<(ostream & i, int n) { retum i, } int main) { cout << § << endl; cinget(), retum 0, y a 5 ») 6 ¢) error d) runtime error 6.9 Questions and Exercises 1 2 3 4 5 6 7. 8 8 1 What is operator overloading? What is an operator function? Define unary operator Define binary operator What is the difference between unary and binary averioading? A friend function cannot be used to overload the assignment operator. Explain why? Explain the rules of operator overloading. Describe the syntax of an operator function, Why is itnecessary to overload an operator? 0. What is type conversion 6.10 Key Terms Operator function: the function that overloads an operator (Operator overloading: allows the programmer to extend the definitions of most of the operators so that operators-such as relational operators, arithmetic operators, the insertion operator for data output. and the extraction operator for data input-can be used to manipulate class objects Parameterized types: class templates are called parameterized types because, based on the parameter type, a specific class is generate, Friend function: a function that is defined outside the scope of @ class, itis @ nonmember function of the class but it has access to the private data members of the class Function template: allows you to write a single code segment for a set of related functions Check Your Progress: Answers 1 b). operator overloading 141 Notes 142 Notes a a a 8) a) b) a) a) a) a) d) 10. ¢) ‘operator operator sign 63 Volume of Boxt 210 Volume of Box2 : 1860 Volume of Box3 : £400 operator operator+= 1010 None of the mentioned both a & b error 6.11 Further Readings Balagurusamy (2008) Object Oriented Programming With C++ Tata McGraw-Hill Education, Subhash, K. U. (2010) Object Oriented Programming With C++ Pearson Education India. Ramesh Vasappanavara, Anand Vasappenavare, Gautam Vasappanavara, Pearson Education India ‘Object Oriented Programming wit C+

You might also like