I NTRODUCING O PERATOR O VERLOADING Chapter 6 Department of CSE, BUET 1.

Slides:



Advertisements
Similar presentations
Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
Advertisements

Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
I NHERITANCE Chapter 7 Department of CSE, BUET 1.
Review of Inheritance. 2 Several Levels of Inheritance Base Class B Derived class D Derived class D1.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Chapter 8. Operator Overloading Operator overloading gives the opportunity to redefine C++ Operator overloading refers to redefine C++ operators such.
Operator Overloading Fundamentals
T EMPLATES Chapter 11 (11.1 and 11.2 only) Department of CSE, BUET 1.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
1 CS 201 Introduction to c++ (2) Debzani Deb. 2 Classes (1) A class definition – in a header file :.h file A class implementation – in a.cc,.cpp file.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
1 Operator Overloading. 2 Syntax The general syntax is: [friend] returntype operator ( ) { ; }
Chapter 13: Overloading.
Chapter 15: Operator Overloading
Operator overloading Object Oriented Programming.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
Operator Overloading Customised behaviour of operators Unit - 06.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Overloading Operators. Operators  Operators are functions, but with a different kind of name – a symbol.  Functions.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Function and Operator Overloading. Overloading Review of function overloading –It is giving several definitions to a single function name –The compiler.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Operator Overloading in C++. Operator Overloading It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it.
Operator overloading and type convesions BCAS,Bapatla B.mohini devi.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
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.
CS Object Oriented Programming Using C++
OPERATOR OVERLOADING Customised behaviour of operators.
CONSTRUCTOR AND DESTRUCTORS
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
Unit VI polymorphism. Md.Jaffar Sadiqsumalatha Polymorphism refers to : one name, many forms. Polymorphism is of two types:  Compile time polymorphism.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
CSCI-383 Object-Oriented Programming & Design Lecture 11.
1 CSC241: Object Oriented Programming Lecture No 08.
Dale Roberts 1 Operator Overloading Member Functions Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 07: Object Oriented Programming:2014 Object-Oriented Programming in C++ Operator.
Programming with ANSI C ++
Operator Overloading.
CSE1002 – Problem Solving with Object Oriented Programming
Overloading C++ supports the concept of overloading Two main types
Operator Overloading Ritika Sharma.
Chapter 13: Overloading and Templates
Chapter 7: Expressions and Assignment Statements
Operator Overloading; String and Array Objects
Introduction Rules Types Programs
Object-Oriented Design (OOD) and C++
Class A { public : Int x; A()
Objectives Define polymorphism Overload functions
Constructor & Destructor
Chapter 15: Overloading and Templates
Operator Overloading BCA Sem III K.I.R.A.S.
Virtual Functions Department of CSE, BUET Chapter 10.
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading.
INTERNATIONAL INSTITUTE OF IFORMATION TECHNOLOGY, (I²IT)
Review of Function Overloading
Presentation transcript:

I NTRODUCING O PERATOR O VERLOADING Chapter 6 Department of CSE, BUET 1

O BJECTIVES The basics of operator overloading Overloading binary operators Overloading the relational and logical operators Overloading a unary operator Using friend operator functions A closer look at the assignment operator Overloading the [ ] subscript operator 2 Department of CSE, BUET

T HE B ASICS OF O PERATOR O VERLOADING Allows the programmer to define the meaning of the C++ operators relative to programmer defined classes Resembles function overloading An operator is always overloaded relative to a user-defined type, such as a class When overloaded, the operator loses none of its original meaning To overload an operator, we create an operator function An operator function can be A member of the class for which it is defined A friend of the class for which it is defined 3 Department of CSE, BUET

T HE B ASICS OF O PERATOR O VERLOADING ( CONTD.) General form of a member operator function return-type class-name::operator#(arg-list) { … } Restrictions: The precedence of the operator cannot be changed The number of operands that an operator takes cannot be altered The following operators cannot be overloaded. ::.* ? preprocessor operators Except for the =, operator functions are inherited by any derived class. Operator functions can be further overloaded in the derived classes. Operator functions cannot have default arguments. 4 Department of CSE, BUET

O VERLOADING B INARY O PERATORS Department of CSE, BUET 5 class coord { int x, y; public: coord(int a = 0, int b = 0) { x = a; y = b; } void show() { cout << x << “, ” << y << endl; } coord operator+(coord obj); coord operator+(int i); coord operator-(coord obj); coord operator=(coord obj); }; coord coord::operator+(coord obj) { coord temp; temp.x = x + obj.x; temp.y = y + obj.y; return temp; } coord coord::operator+(int i) { coord temp; temp.x = x + i; temp.y = y + i; return temp; }

O VERLOADING B INARY O PERATORS ( CONTD.) Department of CSE, BUET 6 coord coord::operator-(coord obj) { coord temp; temp.x = x - obj.x; temp.y = y - obj.y; return temp; } coord coord::operator=(coord obj) { x = obj.x; y = obj.y; return *this; } void main() { coord c1(20, 20), c2(10, 10); coord c3 = c1 + c2; // c1.+(c2) c3.show(); // 30, 30 coord c4 = c3 + 5; // c3.+(5) c4.show(); // 35, 35 coord c5 = c2 – c1; // c2.-(c1) c5.show(); // -10, -10 coord c6 = c1 + c2 + c3; // (c1.+(c2)).+(c3) c6.show(); // 60, 60 (c6 – c4).show(); // 25, 25 c5 = c6 = c6 – c1; // c5.=(c6.=(c6.-(c1))) c5.show(); // 40, 40 c6.show(); // 40, 40 }

O VERLOADING T HE R ELATIONAL AND L OGICAL O PERATORS Department of CSE, BUET 7 class coord { int x, y; public: coord(int a = 0, int b = 0) { x = a; y = b; } void show() { cout << x << “, ” << y << endl; } int operator==(coord obj); int operator!=(coord obj); int operator&&(coord obj); int operator||(coord obj); }; int coord::operator==(coord obj) { return (x == obj.x) && (y == obj.y); } int coord::operator!=(coord obj) { return (x != obj.x) || (y != obj.y); } int coord::operator&&(coord obj) { return (x && obj.x) && (y && obj.y); } int coord::operator||(coord obj) { return (x || obj.x) || (y || obj.y); }

O VERLOADING A U NARY O PERATOR Department of CSE, BUET 8 class coord { int x, y; public: coord(int a = 0, int b = 0) { x = a; y = b; } void show() { cout << x << “, ” << y << endl; } coord operator++(); coord operator++(int unused); coord operator-(); coord operator-(coord obj); }; coord coord::operator++() { ++x; ++y; return *this; } // prefix version coord coord::operator++(int unused) { coord temp; temp.x = x++; temp.y = y++; return temp; } // postfix version coord coord::operator-() { coord temp; temp.x = -x; temp.y = -y; return temp; } coord coord::operator-(coord obj) { coord temp; temp.x = x-obj.x; temp.y = y-obj.y; return temp; }

O VERLOADING A U NARY O PERATOR ( CONTD.) Department of CSE, BUET 9 void main() { coord c1(10, 10), c2(10, 10); coord c3 = ++c1; // c1.++() coord c4 = c2++; // c2.++(0) c1.show(); // 11, 11 c2.show(); // 11, 11 c3.show(); // 11, 11 c4.show(); // 11, 11 coord c5 = -c1; // c1.-() c1.show(); // 11, 11 c5.show(); // -11, -11 coord c6 = c3 – c4; // c3.-(c4) c6.show(); // 0, 0 } Here, prefix “++” and postfix “++” produces the same result.

O BJECT C OPY I SSUES Whenever possible we should use reference parameters while passing objects to or returning objects from a function. coord coord::operator+(coord& obj) { … } coord& coord::operator=(coord& obj) { … } coord& coord::operator++() { … } Otherwise should use copy constructors to overcome object copy problems. 10 Department of CSE, BUET Why not use & here???

U SING F RIEND O PERATOR F UNCTIONS It is possible to overload an operator relative to a class by using a friend rather than a member function. As a friend function does not have a this pointer – For binary operators, both operands must be passed explicitly For unary operators, the single operand must be passed explicitly Allows us to perform operations like - coord c1(10, 10), c2; c2 = 10 + c1; We cannot perform this using member operator functions as the left argument of ‘+’ is not an object of class “coord” We cannot use a friend to overload the assignment operator (=) It can be overloaded only by a member operator function 11 Department of CSE, BUET

U SING F RIEND O PERATOR F UNCTIONS ( CONTD.) Department of CSE, BUET 12 class coord { int x, y; public: coord(int a = 0, int b = 0) { x = a; y = b; } void show() { cout << x << “, ” << y << endl; } friend coord operator+(coord &ob1, coord &ob2); friend coord operator+(int i, coord &ob); friend coord& operator++(coord &ob); }; coord operator+(coord &ob1, coord &ob2) { coord temp; temp.x = ob1.x + ob2.x; temp.y = ob1.y + ob2.y; return temp; } coord operator+(int i, coord &ob) { coord temp; temp.x = ob.x + i; temp.y = ob.y + i; return temp; }

U SING F RIEND O PERATOR F UNCTIONS ( CONTD.) Department of CSE, BUET 13 coord & operator++(coord & ob) { ob.x++; ob.y++; return ob ; } Here, in case of “++” we must use reference parameter. Otherwise changes made inside the function will not be visible outside and the original object will remain unchanged. void main() { coord c1(20, 20), c2(10, 10); coord c3 = c1 + c2; // +(c1, c2) c3.show(); // 30, 30 coord c4 = 5 + c3; // +(5, c3) c4.show(); // 35, 35 ++c4; // ++(c4) c4.show(); // 36, 36 }

A C LOSER L OOK AT THE A SSIGNMENT O PERATOR By default, “ob1 = ob2” places a bitwise copy of “ob2” into “ob1” This causes problem when class members point to dynamically allocated memory Copy constructor is of no use in this case as it is an assignment, not an initialization So, we need to overload ‘=’ to overcome such problems 14 Department of CSE, BUET

A C LOSER L OOK AT THE A SSIGNMENT O PERATOR ( CONTD.) Department of CSE, BUET 15 class strtype { char *p; int len; public: strtype(char *s) { len = strlen(s) + 1; p = new char[len]; strcpy(p, s); } ~strtype() { delete [ ] p; } strtype &operator=(strtype &ob); }; strtype &strtype::operator=(strtype &ob) { if(len < ob.len) { delete [ ] p; p = new char[ob.len]; } len = ob.len; strcpy(p, ob.p); return *this; } void main() { strtype s1(“BUET”), s2(“CSE”); s1 = s2; // no problem }

A C LOSER L OOK AT THE A SSIGNMENT O PERATOR ( CONTD.) The overloaded ‘=’ operator must return *this to allow chains of assignments ob1 = ob2 = ob3 = ob4; If the overloaded ‘=’ operator returns nothing (void) then ob1 = ob2; is possible, but ob1 = ob2 = ob3; produces compiler error ob3 can be assigned to ob2, but then it becomes “ob1 = (void)” So, the compiler detects it early and flags it as an error Whenever possible we should use references while passing objects to functions Copy constructors can also help in this regard but using references is more efficient as no copy is performed 16 Department of CSE, BUET

A C LOSER L OOK AT THE A SSIGNMENT O PERATOR ( CONTD.) Department of CSE, BUET 17 Overloading the ‘=’ operator, we can assign object of one class to an object of another class class yourclass { … }; class myclass { public: myclass& operator=(yourclass &obj) { // assignment activities return *this; }; void main( ) { myclass m1, m2; yourclass y; m1 = y; m2 = m1; // no problem default bitwise copy is done }

O VERLOADING THE [ ] S UBSCRIPT O PERATOR In C++, the [ ] is considered a binary operator for the purposes of overloading The [ ] can be overloaded only by a member function General syntax ret-type class-name::operator[ ](int index) {…} “index” does not have to be of type “int” “index” can be of any other type ret-type class-name::operator[ ](char *index) {…} It is useful when the class has some array like behavior 18 Department of CSE, BUET

O VERLOADING THE [ ] S UBSCRIPT O PERATOR (E XAMPLE - 1) Department of CSE, BUET 19 class array { int a[3]; public: array() { for(int i=0; i<3; i++) a[i] = i; } int operator[ ](int i) { return a[i]; } int operator[ ](char *s); }; int array::operator[ ](char *s) { if(strcmp(s, “zero”)==0) return a[0]; else if(strcmp(s, “one”)==0) return a[1]; else if(strcmp(s, “two”)==0) return a[2]; return -1; } void main() { array ob; cout << ob[1]; // 1 cout << ob[“two”]; // 2 ob[0] = 5; // compiler error // ob[i] is not an l-value in this example }

O VERLOADING THE [ ] S UBSCRIPT O PERATOR (E XAMPLE - 2) Department of CSE, BUET 20 class array { int a[3]; public: array() { for(int i=0; i<3; i++) a[i] = i; } int & operator[ ](int i) { return a[i]; } int & operator[ ](char *s); }; int & array::operator[ ](char *s) { if(strcmp(s, “zero”)==0) return a[0]; else if(strcmp(s, “one”)==0) return a[1]; else if(strcmp(s, “two”)==0) return a[2]; return a[0]; } void main() { array ob; cout << ob[1]; // 1 cout << ob[“two”]; // 2 ob[0] = 5; // no problem // ob[i] is now both an l-value and r-value cout << ob[“zero”]; // 5 }

N OTE ON L - VALUE An l-value is an expression that can appear on both the left-hand and right-hand side of an assignment It represents a location not just a value Based on its placement, either the location or the value is used by the compiler int x, y; x = 0; y = x; Here both x and y are l-values Generally if a function returns a value of any type, then it cannot be used as an l-value int f1( ) { int x = 0; return x; } int n = f1( ); // no problem f1( ) = n; // compiler error, need a location to place a value 21 Department of CSE, BUET

N OTE ON L - VALUE ( CONTD.) But if a function returns a reference of any type, then it can be used both as an l-value and r-value int x; // global variable int& f1( ) { return x; } int n = f1( ); // no problem Works like “int n = x” f1( ) = n; // no problem Works like “x = n” Data can be both fetched from and written into an l-value 22 Department of CSE, BUET

N OTE ON R - VALUE If an expression is just an r-value then it cannot appear on the left-hand side of an assignment It represents just a value int x = 3; // x is both an l-value and r-value 3 = x; // compiler error, 3 is just an r-value, not an l-value Generally if a function returns a value of any type, then it can only be used as an r-value int f1( ) { int x = 2; return x; } int n = f1( ); // no problem cout << f1( ); // no problem, prints ‘2’ f1( ) = n; // compiler error 23 Department of CSE, BUET

L ECTURE C ONTENTS Teach Yourself C++ Chapter 6 (Full, with exercises) Study all the examples from the book carefully 24 Department of CSE, BUET