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

Slides:



Advertisements
Similar presentations
Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
Advertisements

CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Operator Overloading Fundamentals
Chapter 7: User-Defined Functions II
Class and Objects.
Operator Overloading. Basics Define operations on user-defined data types –Perform same operation as it is supposed to but, with operands of the user-defined.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Classes: A Deeper Look Systems Programming.
A Deeper Look at Classes CS-2303, C-Term A Deeper Look at Classes CS-2303 System Programming Concepts (Slides include materials from The C Programming.
Chapter 13: Overloading.
Chapter 15: Operator Overloading
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
Operator Overloading and Type Conversions
OPERATOR OVERLOADING. Closely related to function overloading is - operator overloading. In C++ you can overload most operators so that they perform special.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Inheritance Inheritance – most important and a useful feature of OOPs supported by C++ | Website for Students | VTU -NOTES -Question Papers.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Operator Overloading Operator Overloading allows a programmer to define new types from the built-in types. –Operator Overloading is useful for redefining.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
OPERATOR OVERLOADING. Closely related to function overloading is - operator overloading. In C++ you can overload most operators so that they perform special.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
Operator Overloading.
CSE1002 – Problem Solving with Object Oriented Programming
Constructors and Destructors
Chapter 13: Overloading and Templates
Chapter 7: User-Defined Functions II
Operator Overloading; String and Array Objects
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Java Primer 1: Types, Classes and Operators
Constructor & Destructor
Chapter 15: Overloading and Templates
OPERATOR OVERLOADING.
CS212: Object Oriented Analysis and Design
Operator Overloading; String and Array Objects
Operator Overloading; String and Array Objects
Constructors and Destructors
Operator overloading Dr. Bhargavi Goswami
Constructors and Destructors
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
A Deeper Look at Classes
Presentation transcript:

OPERATOR OVERLOADING Understand Operator Overloading and how it is implemented in C++ ? | 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. | 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) | Website for students | VTU NOTES

Overloading Operators – The Syntax * important* Examples - void operator –(); stack prgm void operator +(int); friend ostream &operator <<(ostream&, complex); class { operator (arg_list); }; member function definition outside the class class name ::operator (arg_list) { //function body } | 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 | Website for students | VTU NOTES

Syntax for member functions that overload a given operator - Class { return_type> operator ; //prototype list } return_type> operator //definition { //Function body } | 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. | Website for students | VTU NOTES

Syntax for a friend function that overloads a given operator is as follows Class { Friend operator ; //prototype }; return_type> operator { //function body } Friend function takes 1 argument more that the Member function that serves the same purpose. | 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 { operator friend operator ; //prototype }; operator { //function body } | Website for students | VTU NOTES

Example void operator +(int); friend ostream &operator <<(ostream &, Date); Class { operator Friend operator ; //prototype }; operator { //function body } Friend function takes 1 argument more than the Member function that serves the same purpose. | 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 | 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 | 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 } | 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*/ | 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 | 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*/ } | 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 | 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()*/ } | 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); | 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. | 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 | 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 | Website for students | VTU NOTES

Class A { public: A operator +(const B &); }; Compiler will interpret the statement a2=b1+a1; | 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. | 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 | 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. | 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. | 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 | 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. | 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 | Website for students | VTU NOTES

Definition of string::add() function can be same as operator overloading function to overload 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. | 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(); | 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 | 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 a b c ‘\0’ cStr s1 s | 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. | 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 | 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. | 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. | 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 | 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 | Website for students | VTU NOTES

Some of the existing operators cannot be overloaded Following operators cannot be overloaded: 1. :: scope Resolution operator 2..(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) | Website for students | VTU NOTES

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 using static functions | 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 | 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 &); }; | 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. | 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 ++(); 1. Operator Overloading function should first increment iFeet 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 | 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*/ | 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. | 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); | 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. | Website for students | VTU NOTES

Class Distance { public: Distance operator ++();//prefix //notation Distance operator ++(int);//postfix //notation & rest of Distance class }; Distance operator ++() { return Distance(++iFeet, fInches); } | Website for students | VTU NOTES