operator overloading

51
OPERATOR OVERLOADING Understand Operator Overloading and how it is implemented in C++ ? www.bookspar.com | Website for students | VTU NOTES

Upload: audra-hoffman

Post on 01-Jan-2016

61 views

Category:

Documents


0 download

DESCRIPTION

Operator Overloading. Understand Operator Overloading and how it is implemented in C++ ?. Basic Definition of Operator Loading. Programming an operator to work on operand of object types. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Operator Overloading

OPERATOR OVERLOADING

Understand Operator Overloading and how it is implemented in C++ ?

www.bookspar.com | Website for students | VTU NOTES

Page 2: Operator Overloading

Basic Definition of Operator Loading

Programming an operator to work on operand of object types.

Eg – addition operator work on operands of type char, int, float and double. If s1,s2,s3 are objects of class string, then statement s3=s1+s2; will not compile unless the creator of class string overloads addition operator to work on the objects of his class.

www.bookspar.com | Website for students | VTU NOTES

Page 3: Operator Overloading

Some of the Operator overloading functions prototypes found in lab

friend ostream &operator <<(ostream &, Date);void operator +(int );void operator –();friend ostream &operator <<(ostream &, STACK );

friend ostream &operator <<(ostream& , complex);friend ostream &operator <<(ostream& , matrix);matrix operator ==(matrix)

www.bookspar.com | Website for students | VTU NOTES

Page 4: Operator Overloading

Overloading Operators – The Syntax * important*Examples - void operator –(); stack prgmvoid operator +(int);friend ostream &operator <<(ostream& , complex);

class <class name>{

<return_type> operator <op> (arg_list);};

member function definition outside the class<return_type> class name ::operator <op> (arg_list){

//function body}

www.bookspar.com | Website for students | VTU NOTES

Page 5: Operator Overloading

• Operators are overloaded by writing operator-overloading functions.

• Operator overloading functions are either member functions / friend functions of that class whose objects are intended as operands of the overloaded operator.

• Similar to the member functions and friend functions.

• Names of overloading functions are composed of keyword operator followed by the symbol of operator being overloaded

www.bookspar.com | Website for students | VTU NOTES

Page 6: Operator Overloading

Syntax for member functions that overload a given operator -

Class <class_name>{return_type> operator <op> <arg_list>; //prototype list

}return_type> operator <op> <arg_list>//definition{//Function body

}

www.bookspar.com | Website for students | VTU NOTES

Page 7: Operator Overloading

Member functions that overload operators can be private , protected or public

• The prototype of operator overloading function specifies a return type

• Keyword operator follows a return type.

• This inturn is followed by the symbol of operator being overloaded.

• A pair of parentheses containing the formal arguments is specified.

www.bookspar.com | Website for students | VTU NOTES

Page 8: Operator Overloading

Syntax for a friend function that overloads a given operator is as follows

Class <class_name>{Friend <return_type> operator <op> <arg_list>;//prototype};return_type> operator <op> <arg_list>{//function body}Friend function takes 1 argument more that the

Member function that serves the same purpose.

www.bookspar.com | Website for students | VTU NOTES

Page 9: Operator Overloading

class stack{Private : int a[10],size,top;Public:

void operator +(int);void operator –(); //mf prototypesfriend ostream &operator <<(ostream &out , stack t);};

class <class_name>{ <return_type> operator <op> <arg_list>friend <return_type> operator <op> <arg_list>;//prototype};

<return_type> operator <op> <arg_list>{//function body}

www.bookspar.com | Website for students | VTU NOTES

Page 10: Operator Overloading

Example void operator +(int);

friend ostream &operator <<(ostream &, Date);

Class <class_name>{<return_type> operator <op> <arg_list>Friend <return_type> operator <op> <arg_list>;//prototype};<return_type> operator <op> <arg_list>{//function body}Friend function takes 1 argument more than the Member function that serves the same purpose.

www.bookspar.com | Website for students | VTU NOTES

Page 11: Operator Overloading

because the invoking object appearing as an explicit parameter to the friend function whereas in member functions it is passed as an implicit parameter.

Same holds true in case of operatorloading functions

www.bookspar.com | Website for students | VTU NOTES

Page 12: Operator Overloading

Examples help in clarifying syntax

• Suppose we want to overload the addition operator(+) so that it can take objects of class String

www.bookspar.com | Website for students | VTU NOTES

Page 13: Operator Overloading

Syntax in case of member functions would be//string.cppClass String{public:String operator +(const String &) const; //prototype

//rest of the class String}

www.bookspar.com | Website for students | VTU NOTES

Page 14: Operator Overloading

String String :: operator +(const String & ss) const

//function definition outside class

{

//function body

}

/* definition rest of the functions of class String*/

www.bookspar.com | Website for students | VTU NOTES

Page 15: Operator Overloading

//someprogram.cpp

void f() //some function{String s1,s2,s3;/*rest of the function f()*/S3=s1+s2;/*rest of the function f()*/}

Defining & using operator-overloading function as a member function

www.bookspar.com | Website for students | VTU NOTES

Page 16: Operator Overloading

Function f() has been declared as a publicmember of the class because operator will beused in its overloaded form within the nonmember functions.If this function is to be declared as a friend , then the syntax would be as follows –

//String.hclass String{friend String operator +(const String &, constString) //Prototype/*rest of the function*/}

www.bookspar.com | Website for students | VTU NOTES

Page 17: Operator Overloading

//string.cpp#include “String.h”

String operator + (const String &, const String & ss) const //definition{//function body}/*definitions of rest of the functions of class String*/

//someprogram.cpp

www.bookspar.com | Website for students | VTU NOTES

Page 18: Operator Overloading

//someprogram.cppVoid f() //some function{ String s1,s2,s3;/*rest of the function f()*/ s3=s1+s2;/*rest of the function f()*/}

www.bookspar.com | Website for students | VTU NOTES

Page 19: Operator Overloading

How does the compiler interpret the overloading functions ? /*important*/

The statement s3=s1+s2;//s1,s2 and s3 are the objects of class StringIs interpreted asS3=s1.operator +(s2);If operator overloading function has been declared as a member function, then this interpretation is satisfied.

Else the statement is interpreted asS3=operator +(s1,s2);

www.bookspar.com | Website for students | VTU NOTES

Page 20: Operator Overloading

If operator-overloading function has been declared as friend, then this interpretation is satisfied, else compiler reports an error

• Compiler doesn’t say that invalid operands have been passed to the operator.

• Operators have been overloaded within classes using member functions / friend functions. These functions are compiled and stored in the library.

• Compilers convert the statements where the overloaded operators are used.

www.bookspar.com | Website for students | VTU NOTES

Page 21: Operator Overloading

• Operator-overloading functions can be called directly from within main() / application program like this

S3=s1.operator +(s2); //in case of member functions

ORS3=operator +(s1,s2); //in case of friend functions

www.bookspar.com | Website for students | VTU NOTES

Page 22: Operator Overloading

Operator-overloading functions are implemented like ordinary member / non-member / friend functions

Why overload using Friend Functions ? / whyfriend functions are used to overload operators ?Lets consider 2 classes A (which we have defined) & B (an existing class).

For some reason, only an object of class A, Objects of class B will appear on left side of the operator.a2=b1+a1; //a1,a2 are objects of class A, b1 is an object of the class B

Lets assume further that there is no means tomodify the definition of class B. If we define theoperator overloading function as a mf of class AAs follows

www.bookspar.com | Website for students | VTU NOTES

Page 23: Operator Overloading

Class A

{

public:

A operator +(const B &);

};

Compiler will interpret the statement

a2=b1+a1;

www.bookspar.com | Website for students | VTU NOTES

Page 24: Operator Overloading

Compiler will interpret the statementa2=b1+a1;

First as A2=b1.operator +(a1);And then asA2=operator +(b1,a1);Prototype of mf doesnt satisfy either of these

Interpretations. Compiler will naturally throw anerror. Declaring the operator-overloadingfunction as a friend function with an object ofclass B as first formal argument solves theproblem.

www.bookspar.com | Website for students | VTU NOTES

Page 25: Operator Overloading

Class A {public:friend A operator +(const B &, const A &); //prototype

};

A operator +(const B &bb, const A &aa)//definition

{//function body}Operator overloading using friend function

www.bookspar.com | Website for students | VTU NOTES

Page 26: Operator Overloading

• NOTE – Compiler throws an error if both member function and friend function are used to overload an operator.

• Reason – Both of them will satisfy calls to the overloaded operator.

• Compiler can’t decide with which function such a call is to be resolved.

www.bookspar.com | Website for students | VTU NOTES

Page 27: Operator Overloading

Overloading of Unary & Binary Operators

• Member functions that overload unary operators take no operands because no parameter is passed to operator and calling object is passed as an implicit parameter to the object.

• Friend functions that overload unary operators will take 1 parameter since the calling object will be passed as an explicit parameter to it.

www.bookspar.com | Website for students | VTU NOTES

Page 28: Operator Overloading

• Similarly mfs that overload binary operators will take 1 parameter.

• Reason – Apart from calling object, another value will be passed to operator as an operand( binary operators take 2 operands).

• Calling object will itself be passed to the function as an implicit parameter.

• Friend functions take 1 operand more i.e. 2 operands

www.bookspar.com | Website for students | VTU NOTES

Page 29: Operator Overloading

Why operators are overloaded ? /*important*/Overloaded functions can be easily

Substituted by member functions / friend

functions with meaningful & relevant names.

Eg – operator-overloading function to overload the addition operator (+) for objects of the class String can be easily replaced by a member function of a proper name.

www.bookspar.com | Website for students | VTU NOTES

Page 30: Operator Overloading

Class String{public:

//string operator +(const String &);String add(const String &); //prototype

}String add(const String & ss){ //function body }Void f(){ String s1,s2,s3;/*rof*/S3=s1.add(s2);//*rof*/}Using an ordinary mf to substitute an operatoroverloading function

www.bookspar.com | Website for students | VTU NOTES

Page 31: Operator Overloading

Definition of string::add() function can be same as operator overloading function tooverload addition operator(+).Operator Overloading becomes mandatory

under following circumstances: /*important*/

• Objects of the class acquire resources dynamically during runtime and no 2 objects should share the same copy of the resource.

• Objects of the class acquire some resources dynamically during runtime and no 2 objects should share even different copies of the resource.

www.bookspar.com | Website for students | VTU NOTES

Page 32: Operator Overloading

Objects need to be passed as parameters in

Function templates and operators being used on

template class objects within the template functions

should work in same way on objects of the class.

The default action of dynamic memory management operators (new & delete ) are unsuitable for the class being designed.

Change in implementation of the class forces an undesirable change in its interface in turn necessitating the rewriting and recompiling of the application programs.

Overloading provides better readability of the code i.e. a factor to be considered. The statement

o2=++o1;

is more readable than a statement like

o2=o1.pre_fix_increment();

www.bookspar.com | Website for students | VTU NOTES

Page 33: Operator Overloading

Let us understand these circumstances 1 by one.

Case 1 – Reconsider the class String.What happens at end of the followingblock of code ?String s1(“abc”), s2;S2=s1;

Code for Undesirable default action of theassignment operator

www.bookspar.com | Website for students | VTU NOTES

Page 34: Operator Overloading

As a result of second statement of the code , following scenario emerges

Diagram showing draw back in default action of assignment

a b c ‘\0’101

4

101

4

cStr

cStr

s1

s2

101 102 103 104

www.bookspar.com | Website for students | VTU NOTES

Page 35: Operator Overloading

As a result of Second statement of the code, the pointers embedded in both objects point at the same dynamically allocated memory block.• The default action of the assignment operator simply

copies the value of the pointer embedded in s1 into the pointer embedded in s2.

• Undesirable situation arise due to the absence of copy constructor

• Operator overloading is mandatory for a class whose objects which dont share dynamically allocated resources.

• o1=o2; statement shouldn’t compile at all.

//o1,o2 are objects of the said class.

www.bookspar.com | Website for students | VTU NOTES

Page 36: Operator Overloading

Declare the function overload the assignment operator in private section of the class

• Any use of assignment operator within a non-member function will launch a call to this operator overloading function.

• Since the function is private, such a call will throw a compile-time error.

• Use of assignment operator will be prevented.• If we inadvertently use an assignment operator within

the member function / friend function, private nature of function is not enough to prevent such a call. Such calls can be prevented by not defining the function to overload the assignment operator leading to a linker error

www.bookspar.com | Website for students | VTU NOTES

Page 37: Operator Overloading

The New operator does a number of things by default, some / all of which is not desirable for class being designed• By default, the new operator throws an exception if it fails to allocate the amount of memory requested.

• In response to this out-of-memory condition, class designer need a call to 1 of the member function of the class that can be fulfilled by overloading.

• New operator stores the amount of memory allocated in the memory itself, enabling the delete operator to find size of memory allocated so that it can deallocate the same.

www.bookspar.com | Website for students | VTU NOTES

Page 38: Operator Overloading

Further by default, the new operator simply allocates memory for the object whose type is passed as an operand to it.• Class designer may desire the creating a new object only when new operator is called for the first time.

• Subsequent calls merely return the address of the object that was created in response to the first call to the new operator.

www.bookspar.com | Website for students | VTU NOTES

Page 39: Operator Overloading

Rules for Operator Overloading• New operators cant be created• Following code piece will produce an errorclass A{

public:void operator **();

}; Illegal attempt to create a new operator

www.bookspar.com | Website for students | VTU NOTES

Page 40: Operator Overloading

•Meaning of existing operators cant be changed

• Any operator overloading function (member / friend function) should take atleast 1 operand of the class of which it is a friend.

• Its impossible to change the manner in which an existing operator works on operands of fundamental types( char, int , float , double).

• Following code will not workclass A{ public:

friend int operator +(int , int); //error will //not compile};

An illegal attempt to modify the behaviour of operators onintrinsic types

www.bookspar.com | Website for students | VTU NOTES

Page 41: Operator Overloading

Some of the existing operators cannot be overloaded

• Following operators cannot be overloaded:1.:: scope Resolution operator2..(member selection)3..*(member selection through pointer to member)4.?:(conditional operator)5.sizeof ( finding the size of values and types)6.typeid(finding the type of object pointed at)

www.bookspar.com | Website for students | VTU NOTES

Page 42: Operator Overloading

Some operators can be overloaded using static functions only. They are -

1. =(Assignment operator)2. ( ) (Function operator)3. [ ] (subscripting operator)4. -> (Pointer to member access operator)These operators cannot be overloaded usingstatic functions

www.bookspar.com | Website for students | VTU NOTES

Page 43: Operator Overloading

• Number of arguments that an existing operator takes cannot be changed

• Operator overloading functions should take same number of parameters that operator being overloaded ordinarily takes.

• Eg - the division operator takes 2 arguments. Hence the following class definition causes a compile time error ‘operator’ / takes too few arguments for the operator overloading function.class A{ public:

void operator / (int = 0);};

An illegal attempt to assign a default value to an argumentOf an operator-overloading function

www.bookspar.com | Website for students | VTU NOTES

Page 44: Operator Overloading

It is highly imprudent to modify the values of the operands that are passed to the overloading functions

• Let us consider the function to overload the addition operator for the class stringclass String {

char *cStr;long int len;public:

string operator +(String &);};

www.bookspar.com | Website for students | VTU NOTES

Page 45: Operator Overloading

To guard against modifying lhs and rhs operands of the addition operands in function to overload string , operator overloading function can be overloaded as follows.

class String{

char *cStr;long int len;public:

String operator +(const String &) const;};

making necessary use of the const keyword to preventbugs.

www.bookspar.com | Website for students | VTU NOTES

Page 46: Operator Overloading

Overloading the various operators

• Increment & Decrement operators( prefix and postfix)if d1 and d2 are objects of class Distance, then statement d2=++d1;is interpreted by the compiler as

d2 = d1.operator ++();1. Operator Overloading function should first incrementiFeet portion of d1.2. It should leave fInches part of d1 unaltered.3.It should return the resultant object.With these guidelines, prototype & definition of operator-

overloading function is as follows

www.bookspar.com | Website for students | VTU NOTES

Page 47: Operator Overloading

With these guidelines, prototype & definition of operator-overloading function is as follows

Class Distance{public:

/*rest of the class Distance*/Distance operator ++();

};Distance Distance(++iFeet , fInches){

return Distance(++iFeet,fInches);}/*definitions of rest of the functions of the class*/

www.bookspar.com | Website for students | VTU NOTES

Page 48: Operator Overloading

Operator overloading function should be public because it is called from within functions that are not member functions of class Distance

• It should not be a constant member function since it will modify the value of atleast 1 of data member (iFeet ) of the calling object.

• OO function working is simple• Increment operator works since it is in increment notation.

Hence iFeet member of calling object gets incremented.• Explicit call to constructor creates a nameless object of class

Distance by passing incremented value of iFeet and unaltered value of fInches as parameters.

• OO function returns the nameless object hence constructed.

www.bookspar.com | Website for students | VTU NOTES

Page 49: Operator Overloading

If a call to OO function is on rhs of assignment operator, the If a call to OO function is on rhs of assignment operator, the values of returned object is copied to the object on leftvalues of returned object is copied to the object on left

• A different effect is produced if we write statementd2=d1++;

Here initial value of d1 to be copied to d2 and hence iFeet data member of object d1 to get incremented.

If compiler interprets both statements d2 = ++d1; and d2=d1++;

In identical ways, then there is no need to write 2 differentFunctions. d2=++d1; interprets statement as d2=d1.operator

++(); It interprets the statement d2=d1++; as d2=d1.operator ++(0);

www.bookspar.com | Website for students | VTU NOTES

Page 50: Operator Overloading

It implicitly passes zero as a parameter to call OO function when postfix notation is used.

• If it finds a prototype that matches this call exactly, it compiles without errors / warnings. Since the Compiler looks for int as formal argument, it also gives the solution

• Define an additional oo function to overload the increment operator in post fix notation.

www.bookspar.com | Website for students | VTU NOTES

Page 51: Operator Overloading

Class Distance{public:

Distance operator ++(); //prefix //notation

Distance operator ++(int); //postfix //notation & rest of Distance class

};Distance operator ++(){return Distance(++iFeet, fInches);}

www.bookspar.com | Website for students | VTU NOTES