520 likes | 793 Views
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.
E N D
www.bookspar.com | Website for students | VTU NOTES Operator Overloading Understand Operator Overloading and how it is implemented in C++ ?
www.bookspar.com | Website for students | VTU NOTES 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 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 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 • 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 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 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 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 class stack { Private : int a[10],size,top; Public: void operator +(int); void operator –(); //mf prototypes friend 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 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 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 operator loading functions
www.bookspar.com | Website for students | VTU NOTES 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 Syntax in case of member functions would be //string.cpp Class String { public: String operator +(const String &) const; //prototype //rest of the class String }
www.bookspar.com | Website for students | VTU NOTES 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 //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 Function f() has been declared as a public member of the class because operator will be used in its overloaded form within the non member functions. If this function is to be declared as a friend , then the syntax would be as follows – //String.h class String { friend String operator +(const String &, const String) //Prototype /*rest of the function*/ }
www.bookspar.com | Website for students | VTU NOTES //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 //someprogram.cpp Void 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 How does the compiler interpret the overloading functions ? /*important*/ The statement s3=s1+s2; //s1,s2 and s3 are the objects of class String Is interpreted as S3=s1.operator +(s2); If operator overloading function has been declared as a member function, then this interpretation is satisfied. Else the statement is interpreted as S3=operator +(s1,s2);
www.bookspar.com | Website for students | VTU NOTES 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 • Operator-overloading functions can be called directly from within main() / application program like this S3=s1.operator +(s2); //in case of member functions OR S3=operator +(s1,s2); //in case of friend functions
www.bookspar.com | Website for students | VTU NOTES Operator-overloading functions are implemented like ordinary member / non-member / friend functions Why overload using Friend Functions ? / why friend 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 to modify the definition of class B. If we define the operator overloading function as a mf of class A As follows
www.bookspar.com | Website for students | VTU NOTES Class A { public: A operator +(const B &); }; Compiler will interpret the statement a2=b1+a1;
www.bookspar.com | Website for students | VTU NOTES Compiler will interpret the statement a2=b1+a1; First as A2=b1.operator +(a1); And then as A2=operator +(b1,a1); Prototype of mf doesnt satisfy either of these Interpretations. Compiler will naturally throw an error. Declaring the operator-overloading function as a friend function with an object of class B as first formal argument solves the problem.
www.bookspar.com | Website for students | VTU NOTES 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 • 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 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 • 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 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 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 operator overloading function
www.bookspar.com | Website for students | VTU NOTES 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 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 Let us understand these circumstances 1 by one. Case 1 – Reconsider the class String. What happens at end of the following block of code ? String s1(“abc”), s2; S2=s1; Code for Undesirable default action of the assignment operator
www.bookspar.com | Website for students | VTU NOTES As a result of second statement of the code , following scenario emerges Diagram showing draw back in default action of assignment 101 4 a b c ‘\0’ cStr 101 102 103 104 s1 101 4 cStr s2
www.bookspar.com | Website for students | VTU NOTES 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 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 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 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 Rules for Operator Overloading • New operators cant be created • Following code piece will produce an error class A { public: void operator **(); }; Illegal attempt to create a new operator
www.bookspar.com | Website for students | VTU NOTES 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 work class A { public: friend int operator +(int , int); //error will //not compile }; An illegal attempt to modify the behaviour of operators on intrinsic types
www.bookspar.com | Website for students | VTU NOTES Some of the existing operators cannot be overloaded • Following operators cannot be overloaded: • :: scope Resolution operator • .(member selection) • .*(member selection through pointer to member) • ?:(conditional operator) • sizeof ( finding the size of values and types) • typeid(finding the type of object pointed at)
www.bookspar.com | Website for students | VTU NOTES Some operators can be overloaded using static functions only. They are - • =(Assignment operator) • ( ) (Function operator) • [ ] (subscripting operator) • -> (Pointer to member access operator) These operators cannot be overloaded using static functions
www.bookspar.com | Website for students | VTU NOTES 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 argument Of an operator-overloading function
www.bookspar.com | Website for students | VTU NOTES 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 string class String { char *cStr; long int len; public: string operator +(String &); };
www.bookspar.com | Website for students | VTU NOTES 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 prevent bugs.
www.bookspar.com | Website for students | VTU NOTES 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 ++(); • Operator Overloading function should first increment iFeet portion of d1. 2. It should leave fInches part of d1 unaltered. • 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 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 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 If a call to OO function is on rhs of assignment operator, the values of returned object is copied to the object on left • A different effect is produced if we write statement d2=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 different Functions. 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 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.