OPERATOR OVERLOADING WEEK 4-5 CHAPTER 19. class Money {private:int lira; int kurus; public: Money() {}; Money(int l, int k) { lira=l+ k/100; kurus=k%100;

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Operator Overloading Fundamentals
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Class template Describing a generic class Instantiating classes that are type-specific version of this generic class Also are called parameterized types.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
OOP Spring 2007 – Recitation 31 Object Oriented Programming Spring 2007 Recitation 3.
Class Array template The array class defined in last week manipulate array of integer If we need to define class of array for float, double data type,
Chapter 13: Overloading.
Chapter 15: Operator Overloading
OOP Egar 2008 – Recitation 41 Object Oriented Programming Spring 2006 Recitation 6.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Operator Overloading in 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.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
Object Oriented Programming in C++ Chapter5 Operator Overloading.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
CMSC 202 Lesson 12 Operator Overloading II. Warmup  Overload the + operator to add a Passenger to a Car: class Car { public: // some methods private:
Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator Overloading Like most languages, C++ supports a set of operators for its built-in types. Example: int x=2+3; // x=5 However, most concepts for.
Copyright  Hannu Laine C++-programming Part 4: Operator overloading.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
CS Object Oriented Programming Using C++
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
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.
Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing
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.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
1 CSC241: Object Oriented Programming Lecture No 08.
Friend Functions. Problem u Assuming two Complex objects u How would one add two numbers? W + X Complex operator+(const Complex& w, const Complex& x);
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
Operator Overloading What is operator overloading? Most predefined operators (arithmetic, logic, etc.) in C++ can be overloaded when applied to objects.
Operator Overloading.
Andy Wang Object Oriented Programming in C++ COP 3330
CSE1002 – Problem Solving with Object Oriented Programming
Yan Shi CS/SE 2630 Lecture Notes
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 argument’s value.
Chapter 13: Overloading and Templates
Operator Overloading; String and Array Objects
Visit for more Learning Resources
Object-Oriented Design (OOD) and C++
Operator Overloading Part 2
Operator Overloading; String and Array Objects
Advanced Program Design with C++
Operator Overloading; String and Array Objects
תכנות מכוון עצמים ו- C++ יחידה 06 העמסת אופרטורים
Operator Overloading.
Operator Overloading.
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
COP 3330 Object-oriented Programming in C++
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Presentation transcript:

OPERATOR OVERLOADING WEEK 4-5 CHAPTER 19

class Money {private:int lira; int kurus; public: Money() {}; Money(int l, int k) { lira=l+ k/100; kurus=k%100; } Money toplam(const Money & x) { int l, k; l=x.lira+lira; k =x.kurus+ kurus; Money neww( l, k); return neww;} void print_Money(){ cout<<lira << “TL" <<kurus<< " KURUS“<< endl;} }; void main() {Money m1(3, 550);Money m2(19, 600); Money x= m1.toplam(m2); /*Money m3 = m1 + m2  SYNTAX ERROR!! */ x.print_Money(); /* cout << x;  SYNTAX ERROR!!*/ }

Function Overloading && Operator Overloading C++ supports function overloading; so we can use the same name for two or more functions in the same program C++ language supports operator overloading as well. By overloading an operator, – W e can define our own meaning to the operator whenever we use that operator together with an object of our own defined type.

Operator Overloading Operators that can be overloaded: – arithmetic operators: +, -, *, /, %, ++, --, etc. – relational operators:, >=, etc. – assignment operator: = ; +=,*=,/=,%=, etc. – logical operators: &&, ||, !,|, ~, &,^, etc. – input/output operators: > Operators that can not be overloaded !!!!!!!!!!!!!! – Member selector :. – Member object selector :.* – Scope resolution : :: – Conditional : ?:

Operator Overloading : Three ways 1.Member function ( Class method ) 2.Nonmember (Top level-Global) function 3.Friend Function

1. Operator overloading with Member functions ( a method of the class) Declare methods in the class with names – operator+() – operator-() – operator<() – operator>() – operator!() – … For binary operations (operations which require two operands) you need only one input parameter ( like +,-,%,,= ) Money m1,m2; m1+m2; For unary operations you need no parameters ( like !, -(negation), &(address of)) Money m1,m2; !m1; &m2; -m1;

class Money {private:int lira; int kurus; public:Money(){}; Money(int l, int k) { lira=l+k/100; kurus=k%100; } Money operator+ (const Money & x) // MEMBER FUNCTION { int l, k; l=x.lira-lira; k =x.kurus+ kurus; Money neww( l, k); return neww;} void print_Money() {cout<<lira << “YTL" <<kurus<< " KURUS“<< endl;}; void main() {Money m1(3, 550);Money m2(19, 600); Money x = m1 + m2; //m1.operator+(m2); x.print_Money();} EXAMPLE: Member Function Operator + Overloaded

Operator Overloading with Member Functions “+” and “–” Money Money:: operator+ (const Money & x) // A MEMBER FUNCTION { int l, ks; l=x.lira+lira; k=x.kurus+ kurus; Money neww( l, k ); return neww;} Money Money::operator- (const Money & x) // A MEMBER FUNCTION { int l, k; l=-x.lira+lira; k=-x.kurus+ kurus; Money neww ( l, k ); return neww;} void main() {Money m1(3, 550); Money m2(19, 600); Money x = m1 + m2; Money y= m1 - m2; //m1.operator-(m2) //cout << x; // SYNTAX ERROR!! Operator << is not defined for Money x.print_Money();}

Operator Overloading with Member Functions Binary and Unary “–” Money Money ::operator- (const Money & x) // BINARY OPERATOR NEEDS TWO OPERANDS { int l, k; l=lira-x.lira; k=kurus- x.kurus; Money neww( l, k); return neww;} Money Money ::operator- () // UNARY OPERATOR NEEDS ONLY ONE OPERAND // WILL GET THE NEGATIVE : x  -x { int l, k; l=-lira; k=- kurus; Money neww( l, k); return neww;} void main() {Money m1(3, 550); Money m2(19, 600); Money x = m1 - m2; //m1.operator-(m2); Money y= -m1; //m1.operator-(); x.print_Money(); y.print_Money();}

Operator Overloading with Member Functions : Relational operator == // Money m1(…), m2(….); // if(m1==m2) {…..} // else {…..} bool Money:: operator> (const Money & x) { int total_this, total_x; total_x=x.lira*100+x.kurus; total_this=lira*100+kurus; if(total_this>total_x) return 1; elsereturn 0;}

Operator Precedence Operator precedence and syntax can not be changed through overloading !!! EXAMPLE: Money m1, m2, m3, ans; ans=m1+m2* m3; // is similar with ans=m1+(m2*m3);

2. Operator Overloading with Toplevel (Nonmember- Global) Functions Use functions to overload operators Declare functions like – operator+() //Money operator+(Money&x, Money&y); – operator-() – operator<() – operator!() //Money operator!(Money&x); – … For unary operators function must have one input parameter  !x For binary operators function must have two input parameter  x+y If top level functions tries to access private members, they have to call public methods that return private members ( get methods..)

2. Operator Overloading with Toplevel (Global) Functions class Money {private: int lira, kurus; public: Money(){}; Money(int l, int k) { lira=l+k/100; kurus=k%100; } int get_lira() { return lira;} /* toplevel functions cannot access private members so we have to define methods to return private members */ int get_kurus(){ return kurus;} }; Money operator+ (Money & x, Money &y) { int new_lira=x.get_lira()+y.get_lira(); int new_kurus =x.get_kurus()+ y.get_kurus(); Money neww( new_lira, new_kurus); return neww;} Money operator- (Money & x) // UNARY MINUS-NEGATION { int new_lira=-x.get_lira(); int new_kurus =-x.get_kurus(); static Money neww( new_lira, new_kurus); return neww;} void main() {Money m1(3, 550), m2(19, 600); Money x = m1 + m2; Money y= -m1;}

3. Operator Overloading with Friend Functions A class’s private members are accessible only to 1.its methods 2.its friend functions!!!

3. Operator Overloading with Friend Functions class Money {private: int lira, kurus; public: Money(){}; Money(int l, int k) { lira=l+k/100; kurus=k%100; } void print_Money(){ cout<<lira << " " <<endl;} friend Money operator+(const Money &, const Money &); friend Money operator-(const Money & );}; Money operator+ (const Money & x, const Money &y) { int l=x.lira+y.lira; int k=x.kurus+ y.kurus; static Money neww( l, k); return neww;} Money operator- (const Money & x) // UNARY MINUS-NEGATION { int l=-x.lira; int k =-x.kurus; static Money neww( l, k); return neww;} void main() {Money m1(3, 550), m2(19, 600); Money x = m1 + m2; Money y= -m1; x.print_Money(); y.print_Money(); }

Some Important Remarks For all 3 ways for operator overloading, they are all called in the same way!! Money m1, m2,m3; m3=m1+m2; Remember that parameters to the operators are POSITIONAL  the order of the 1st/ and 2nd parameter does matter Money operator- (Money & x) { int l,k; l=lira-x.lira; k=kurus- x.kurus; //l=x.lira-lira; k=x.kurus- kurus Money neww( l, k); return neww;} Money m1, m2,m3; m3=m1-m2; // m1.operator-(m2);

OVERLOADING THE INPUT AND OUTPUT OPERATORS int i; Money y; cin>>i; cin>>y; are interpreted as operator>>(cin,i); operator>>(cin,y); – Operand >> belongs to a system class (e.g istream) – cin is a istream object – If the leftmost operand must be an object of a different class or a fundamental data type, this operator must be implemented as non-member function or friend function

OVERLOADING THE INPUT AND OUTPUT OPERATORS – To overload >> to read a two integers for Money class (lira and kurus) we can write a top level function istream& operator>>(istream & in,Money &m) {in>>m.lira>>m.kurus; return in;} Use this function as Money m1; cin>>m1; // is equivalent to operator >>(cin, m1) – If you want to use a method to overload >> you have to modify the system class so make it top-level function or friend function!!

#include using namespace std; class Money {friend istream& operator>>(istream &,Money &); private: int lira; int kurus; public:Money(int l, int k) { lira=l+k/100; kurus=k%100; } void print_Money(){ cout<<lira << " " <<kurus<<endl;}}; istream& operator>>(istream &in,Money &m) { in>>m.lira; in>>m.kurus; return in;} void main() {Money m2(0, 0); cin>>m2; //cout << x; // SYNTAX ERROR!! Operator << is not defined for Money m2.print_Money();} EXAMPLE: Operator >> overloaded

OVERLOADING THE INPUT AND OUTPUT OPERATORS – To overload << to print out a two integers for Money class (lira and kurus) we can write a top level function ostream& operator<<(ostream & out,Money &m) {out<<m.lira<<“TL”<<m.kurus<<“KURUS”<<endl; return out;} Use this function as Money m1; cout<<m1; // is equivalent to operator <<(cout, m1) – If you want to use a method to overload << you have to modify the system class so make it top-level function or friend function!!

#include using namespace std; class Money {friend istream& operator>>(istream &,Money &); friend ostream& operator<<(ostream &,Money &); private:int lira; int kurus; public:Money(int l, int k) { lira=l+k/100; kurus=k%100; } }; istream& operator>>(istream &in,Money &m) { in>>m.lira>>m.kurus; return in;} ostream& operator<<(ostream &out,Money &m) { out<<m.lira<<" YTL "<<m.kurus<<" KURUS"<<endl; return out;} void main() {Money m2(0, 0); cin>>m2; cout<<m2; } EXAMPLE: Operator << overloaded

Overloading Assignment Operator = Compiler provides default copy constructor and assignment operator if the author does not provide his own class Money {.... }; void main() { Money m1(10, 1000); Money m2(100, 1000); m1=m2; }

Overloading Assignment Operator = class Money {private:int lira; int kurus; public: Money(int l, int k) { lira=l+k/100; kurus=k%100; } Money & operator=(const Money & x) // will return a reference to m1 { if(this->lira>=x.lira) { lira=x.lira; kurus=x.kurus; } return *this; }}; main() { Money m1(100, 200), m2(30,430); m1=m2; // this is m1 and x is m2 cout<<m1; // << has been overloaded in previous slides }

Senem Kumova Metin OVERLOADING THE [] SUBSCRIPT OPERATOR? #include using namespace std; void main () {int i; int b[5]; for (i=0; i<sizeof (b) / sizeof (b[0]); i++) // i=0 to 4 b[i]=2*i; for (i=0; i<8; i++) cout<<b[i]<<'\n'; } OUTPUT: Press any key to continue b[0] b[4] i

Senem Kumova Metin class myArray { private : int size; int *a; / / a= address of the first element in array public: myArray(int s); ~myArray(); int & operator[] (int i); // a[i] int get_size() const{ return size; } }; EXAMPLE:Overloading Subscript operator []

Senem Kumova Metin int & myArray::operator[] (int i) { if (i =size) { cerr<<“Error: Subscript ”<<i<<“\n Out of Bounds”; exit(0);} return a[i];} myArray::myArray(int s) {a= new int [s]; size=s;} myArray::~myArray() {delete [] a; } void main () {int i; myArray b(5); for (i=0; i<b.get_size(); i++)b[i]=2*i; for (i=0; i<8; i++) cout<<b[i]<<'\n'; } // IMPORTANT NOTE: Subscript operator [] must be overloaded as a method !! EXAMPLE:Overloading Subscript operator [] OUTPUT: Error: Subscript 5 Out of Bounds

Senem Kumova Metin Overloading Function call operator () Overloaded function-call operator does not modify how functions are called; rather, it modifies how the operator is to be interpreted when applied to objects of a given class type Function call operator must be overloaded as a method !! EXAMPLE: class Point { public:Point() { _x = _y = 1; } Point(int x, int y) { _x=x; _y=y;} Point &operator()( int dx, int dy ) { _x += dx; _y += dy; return *this; } friend ostream & operator << (ostream & out, Point & p) { out<<"x = "<<p._x<<" y= "<<p._y<<endl; return out; } private: int _x, _y; }; void main() {Point pt; pt( 3, 2 );cout <<pt; Point pt2(3,2); cout<<pt2; pt2(1,1);cout<<pt2; } OUTPUT: x = 4 y= 3 x = 3 y= 2 x = 4 y= 3 Press any key to continue

Senem Kumova Metin Overloading Increment and Decrement operators The increment ++ and decrement - - operators come in a prefix and a postfix flavor int x = 6; ++x // prefix ++ x++ // postfix ++ We can overload the prefix ++, the postfix ++, the prefix - -, and the postfix - -.

Senem Kumova Metin Overloading Increment and Decrement operators The declaration operator++() refers to the prefix operator ++x The declaration operator++( int ) refers to the postfix operator x++ If the prefix increment operator has been overloaded, the expression ++obj is equivalent to obj.operator++() If the postfix increment has been overloaded, the expression obj++ is equivalent to obj.operator++(0)

Senem Kumova Metin EXAMPLE: Overloading Increment A Clock class will be implemented. If c is a Clock object, c++ advances the time one minute. The value of the expression c++ is the original Clock Executing ++c also advances the time one minute, but the value of the expression ++c is the updated Clock.

Senem Kumova Metin /* Clock.h*/ class Clock { public : friend ostream & operator <<(ostream &out, Clock &p) { out<<setfill('0')<<setw(2)<<p.hour<<":" ; out<<setw(2)<<p.min<<endl; return out; } Clock ( int =12, int =0); Clock tick(); Clock operator++(); //++c Clock operator++(int); // c++ private: int hour; int min;}; EXAMPLE : OVERLOADING INCREMENT OPERATOR

Senem Kumova Metin #include “Clock.h” Clock::Clock ( int h, int m) { hour=h; min=m;} Clock Clock::tick() {++min; if (min>=60) { hour= hour+min/60; min= min%60;} return *this; } Clock Clock::operator ++() {return tick ();} //PREFIX Clock Clock::operator ++(int n)//POSTFIX {Clock c=*this; tick();// this will be incremented return c; // previous value of this will be returned } EXAMPLE : OVERLOADING INCREMENT OPERATOR

Senem Kumova Metin void main(){ Clock c( 12, 50);Clock d; cout <<"Clock c: "<<c; cout <<"Clock d: "<<d; d= c++; cout<<"Clock c: "<<c; cout<<"Clock d: "<<d; cout<<" "<<endl; cout <<"Clock c: "<<c; cout <<"Clock d: "<<d; d= ++c; cout<<"Clock c: "<<c; cout<<"Clock d: "<<d; } EXAMPLE : OVERLOADING INCREMENT OPERATOR