8 Overloading Operators Main Idea Use the same






















![class String - Definition Constructors and class String { Destructors public: String(const char s[]=""); class String - Definition Constructors and class String { Destructors public: String(const char s[]="");](https://slidetodoc.com/presentation_image_h2/b305fb272047d9fa7cf5bac77e9cc5b9/image-23.jpg)







 //Element class String - Subscripts Member Functions returns object char& String: : operator[](unsigned i) //Element](https://slidetodoc.com/presentation_image_h2/b305fb272047d9fa7cf5bac77e9cc5b9/image-31.jpg)





![class String Driver (continued) – I/O String friend. List[5]; cout<<"n. Begin input for list class String Driver (continued) – I/O String friend. List[5]; cout<<"n. Begin input for list](https://slidetodoc.com/presentation_image_h2/b305fb272047d9fa7cf5bac77e9cc5b9/image-37.jpg)


- Slides: 39
8. Overloading Operators Main Idea: Use the same function name (function overload) or operator symbol (operator overload) to perform different computations, initializations or other actions. 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and Operators 1
Overload: Examples Example 2: Overloading the class constructor Assume a complex class type has been defined class Complex {…}; We want to be able to initialize a class object in different ways, e. g. by giving values to its data members or by initializing it to some object of the same class Solution: overload the class constructor, so that argument values of the type of the corresponding data members Complex first(re, im); and Complex second(first); can be used. 11/17/2008 single argument of type Complex, the same type as the object being initialized MET CS 563 - Fall 2008 8. Overloading Functions and Operators 2
Overload: Examples (continued) Example 3: We want to manipulate user defined objects, such as Date class objects or aggregate types such as strings the same way as we manipulate integers or floats, e. g. a) Overloading the '<' operator for Date today < tomorrow should produce true b) the '+' and '==' operator for strings "Welcome " + " home !" should produce "my. Password" == "my. Passwd" should produce 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and Operators "Welcome home !" false 3
Overloading Operators Goal: Manipulate aggregate data types, such as arrays, structures, classes in the same manner as built-in types, i. e. with infix operators that perform user defined operations on the objects. Main Idea: A binary operator is a function with two arguments, e. g. the expression 3+5 that evaluates to 8 is the same as the function plus() plus(3, 5) returning the value 8. Thus operator overload is in essence function overload. In order to implement it we need to write the appropriate definitions and to agree on a way to unambiguously relate these definitions to the operator symbol. Example: operator + {…}, keyword operator - {…} function body overloaded operator Syntax: 11/17/2008 operator <Operator. Symbol> {…} MET CS 563 - Fall 2008 8. Overloading Functions and Operators 4
Implementing Operator Overload: Member Function or friend Function ? A fundamental question of implementing operator overload is: Can we always implement it as a member function of the class or do we need another mechanism as well? We will explore this question by overloading the '+' operator for a user defined class type Rational for rational numbers. The class Rational represents the rational numbers, i. e. all numbers that can be represented as p/ q where p and q are integers, e. g 2/3, 1/4, etc. The class includes the arithmetic and comparison operators and prints the rational number in quotient form by keeping the nominator and denominator as small as possible (as shown in the above examples). 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and Operators 5
Class Rational Interface / Behavior Initialize itself to 0 Perform addition '+' with integers and rationals //other arithmetic operations… Perform comparison '<' with integers and rationals //other comparison operations… Tell its value in reduced quotient form Attributes / Data and Internals nominator denominator reducing the nominator and denominator to smallest value 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and Operators 6
(i) First Try: Overloaded '+' as a Member Function of class Rational{ public: Rational(int n=0, int d=1); //constructor initializing to 0 (0/1) //overloaded '+' prototype //input: single argument of type Rational, //returns value of (input + object) Rational operator+(const Rational& ); … private: int nom; //nominator int denom; //denominator … //functions for reducing nom and denom to smallest values }; 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 7
Class Rational - Constructors and Use of Overloaded '+' Constructor Definition: Rational : : Rational (int n, int d): nom(n), denom(d) {} Object Definitions: Rational t(5, 4), s(3), u, v; Use of Overloaded Operator: function name according to syntax Function Style (acc. Signature): t. operator+(s); Operator Style (Shorthand): 11/17/2008 t + s; MET CS 563 - Fall 2008 8. Overloading Functions and 8
Class Rational - Definition of Overloaded '+' as Member Function Rational : : operator+(const Rational &b ) { Rational sum; sum. nom = b. denom * nom + b. nom * denom; sum. denom = denom * b. denom; sum. reduce(); return sum; } Similar definitions can be written for the remaining binary arithmetic operators such as -, *, /, etc. Use: t. operator+(s); t + s; t + 5; //works as 5 becomes the initial value for argument b 5 + t; // illegal!!! 5 is a literal and 5. operator is not defined!! Problem: t+5 5+t !! when using our new + operator The addition is not commutative contrary to everything we have been taught since elementary school. Not a good idea. 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 9
Class Rational - Declaring Overloaded '+' as friend Function within the class Rational { public: Rational(int n=0, int d=1); //constructor argument 1 argument 2 keyword friend Rational operator+( const Rational&, const Rational&); //overloaded '+' prototype as friend function //input two arguments of type Rational, //returns sum of two arguments … //Similar declarations can be written for the remaining binary //arithmetic operators such as -, *, /, etc. … private: //same as in previous definition int nom; //nominator int denom; //denominator //functions for reducing nom and denom to smallest values }; 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 10
Defining the Overloaded '+' friend Function Outside the Class Rational operator+( const Rational &a, const Rational &b ) Note: The definition has no { indication that Rational sum; there is any relation to some sum. nom = b. denom * a. nom + b. nom * a. denom; class(es). It is a sum. denom = a. denom * b. denom; regular function sum. reduce(); definition and only return sum; the class can give } it special meaning by declaring it a Similar definitions can be written for the remaining binary friend and giving arithmetic operators such as -, *, /, etc. access to its private data members. Use: operator+(t, s); t + s; t + 5; //works as 5 becomes the initial value for argument b 5 + t; // works as well!!! 5 is a literal for argument a!! 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 11
(iii) Overloaded Computer Specific Operators Return Objects Not Just Values Important Shared Characteristics: I/O as well as assignment operators should return objects, not just values to allow compound statements, such as Object of output stream class ostream I/O cout << "The sum is " << a+b; Assignment t += t +s; returns object t modified cout of type ostream resulting from insertion of a+b in previously modified cout 11/17/2008 += a; s = s +a; returns object s modified cout of type ostream resulting from insertion of "The sum is " in cout left-to-right associativity s right -to- left associativity MET CS 563 - Fall 2008 8. Overloading Functions and 12
Overloaded Computer Specific Operators: I/O Friends and Assignment Members Important Difference: I/O cout << a+b; Assignment t += s; lhs and rhs are of different types lhs and rhs are of the same type Input / Output Operators are implemented as friend functions: Assignment Operators are implemented as member functions: 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 13
Another look at class Rational { public: Rational (int = 0, int = 1 ); // default constructor //Arithmetic operators as friend functions friend Rational operator+( const Rational&, const Rational& ); //Similarly the remaining arithmetic operators //Comparison operators as friend functions friend bool operator>( const Rational&, const Rational& ); //Similarly the remaining comparison operators //Output operator as friend function friend ostream& operator<<(ostream& , const Rational& ); //Similarly the input operator //Assignment operators as member functions Rational& operator+=(const Rational& ); //Similarly the remaining assignment operators private: int nom; int denom; int gcd(int , int ); //input: two integers, returns greatest common devisor void reduce( void ); //reduces nom and denom to smallest value}; 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 14
Class Rational - Definition and Use of Overloaded Output Reference as it will change after Prototype in class definition: insertion of expressions to be output friend ostream& operator<<(ostream& , const Rational& ); Definition: Reference: returns class object, not just object value; thus allowing compound operations ostream& operator<<(ostream& out, const Rational& s){ out << s. nom << '/' << s. denom ; return out; } overloaded stream insertion Use: operator Rational d( 3, 9 ); cout << "d = " << argument 1: out 11/17/2008 d << endl; argument 2: s d = 1/3 MET CS 563 - Fall 2008 8. Overloading Functions and 15
Class Rational - Definition and Use of Overloaded Assignment Prototype in class definition: Rational& operator+=(const Rational& ); Reference: returns class object, not just object value; thus Definition: allowing compound operations Rational& Rational : : operator+=(const Rational& r){ nom = nom * r. denom + denom * r. nom; denom *= r. denom; reduce(); Refers to object itself, i. e. object that received message and was modified. return *this; } Use: Rational r(3, 2); cout<< "r = " << r << endl; r = 3/2 cout<< r << "+ 2 ="; 3/2+ 2 =7/2 r += 2; cout<< r << endl; 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 16
The this Pointer Gives Access to Object's Own Address Goal: Provide object with the ability to refer to itself As shown in the overloaded addition assignment this can be quite useful. Solution: Each object is provided with a pointer this that contains the object's address. Note: • The type of the this pointer is given by the type of the corresponding object. • The this pointer is not part of the object itself, i. e. it is not reflected in the result of the sizeof operation that returns the size of an object. It is passed into object as an implicit first argument with every non-static message (call) to the object. • The this pointer is used implicitly or explicitly to reference data members and methods of the class 11/17/2008 MET CS 563 - Fall 2008 8. Overloading Functions and 17
Operators that Cannot Be Overloaded Most operators in C++ can be overloaded. However, the following operators cannot be overloaded . . * 11/17/2008 : : ? : sizeof MET CS 563 - Fall 2008 8. Overloading Functions and 18
7. 3. Class String - (i) C - strings - String literals (constants): sequence of characters enclosed in double quotes, e. g. "I am a string" The internal representation is an array of characters terminated by the NULL character '