1 159.234LECTURE 13 159.234 LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.

Slides:



Advertisements
Similar presentations
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Advertisements

Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Chapter 13: Overloading.
Lecture 5 Constructors Operator Overloads “Absolute C++” Chapters 7.1,8.1,8.2.
Chapter 15: Operator Overloading
OOP Egar 2008 – Recitation 41 Object Oriented Programming Spring 2006 Recitation 6.
Operator Overloading 1. Introduction Let’s define a class for Complex numbers: class Complex { private: double real, image; public: Complex () : real(0.0),
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Operator overloading Object Oriented Programming.
Operator Overloading in C++
1 CSC241: Object Oriented Programming Lecture No 07.
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.
Operator Overloading and Type Conversions
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
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.
1 Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
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.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
Case Study - Fractions Timothy Budd Oregon State University.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
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.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
Chapter 8 Operator Overloading, Friends, and References.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
 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.
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:
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
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;
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.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
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.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
1 CSC241: Object Oriented Programming Lecture No 08.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Operator Overloading.
CSE1002 – Problem Solving with Object Oriented Programming
Operator Overloading Introduction
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
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
Constructor & Destructor
Jim Fawcett Copyright ©
Chapter 15: Overloading and Templates
Operator Overloading
Operator Overloading; String and Array Objects
Operator overloading Dr. Bhargavi Goswami
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
Jim Fawcett Copyright ©
Presentation transcript:

LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment operator Binary operators overloading Overloading I/O operators

2 not const A member function that is not allowed to modify data members of its class is declared as a const member function. class Point { public: Point(): x(0),y(0){}; Point(int a,int b){x = a;y = b;} const void print() const; private: xy int x, y; }; const void Point::print() const { cout <<" x = " << x <<", y = " << y; } const Member Functions

3 CORRECT: const void Point::print() const { cout <<" x = " << x <<", y = " << y;} WRONG: const void Point::print() const x=4; { x=4; cout <<" x = " << x <<", y = " << y;} Error message: Cannot modify a const object. const Member Functions

4 Operator Overloading We have already seen Function overloading. + - Operators + - etc, can also be re-defined! User-defined types can be treated in exactly the same way as simple types. e.g. for a 'complex' type we can allow the addition of two variables. functions Operators can be thought of as functions: -x->negate(x) x+y->add(x,y) natural operators with operator overloading, we use 'natural operators’ rather than having to use functions.

5 Operator Overloading We can overload: arithmetic+ - etc logical&& || comparison> == etc assignment= index[] function() structure pointer-> new, delete 4cannot Only 4 operators cannot be overloaded: dot. conditional?: scope:: sizeof

6 Operator Overloading Although the semantics of an operator can be extended, we cannot change its syntax, the grammatical rules that govern its use, such as the number of operands, precedence and associativity remains the same. e.g. e.g. the multiplication operator will enjoy higher precedence than the addition operator. When an operator is overloaded, its original meaning is not lost. e.g.operator+ e.g. An operator+ that is overloaded to add two vectors, can still be used to add two integers.

7 Defining Operator Overloading To define an additional task to an operator, we must specify what it means in relation to the class to which the operator will be applied. This is done with the help of a special function called operator function which describes the task. General form of an operator function: return type return type classname :: operator  (op-arglist) { function body //task defined } Operator being overloaded operator  is the function name

8 Binary Operator Overloading class clock { public: clock(int seconds=0) : total(seconds) {} operator+ clock operator+(int seconds) { clock temp; temp.total = total + seconds; return temp; } void print(void) {cout << total << endl;} private: total int total; };... clock a(50), b; b = a + 10; b = a + 10; b.print(); e.g. overloading the + operator: There is an i ii implicit first argument (the t tt this pointer). It takes some time to get used to it. Using a member function Allows only expressions with an object on the left-hand side of the operator

9 Binary Operator Overloading class clock { public: clock(int seconds=0) : total(seconds) {} //for construction and conversion operator+ friend clock operator+(clock c1, clock c2); void print(void) {cout << total << endl;} private: int total; }; operator+ clock operator+(clock c1, clock c2) { return (c1.total + c2.total); } e.g. overloading the + operator: It is normal for symmetric Binary operators to be overloaded by friend functions. Using a friend function

10 Unary Operator Overloading e.g. overloading the prefix ++ operator: class clock { public: clock(int seconds=0) : total(seconds) {} operator++ clock operator++() { total++; *this return *this; } void print(void) {cout << total << endl;} private: int total; };... a = ++b; a = ++b; b.print();

11 Overloading the postfix ++ Operator Can we differentiate between prefix and postfix? overloaded ++ In the code previously shown - the compiler uses the overloaded ++ for both postfix and prefix. To create different prefix and postfix versions we need some help from the compiler. postfix version of operator++ with an integer argument: The compiler knows whether the code is prefix or postfix. If it is postfix the compiler uses an 'ad hoc' convention, it tries to find a version of operator++ with an integer argument: operator++ clock operator++(int) { *this clock temp = *this; total++; return temp; } The value of the integer is irrelevant, but it gives us the chance to write two different functions.

12 Overloading the [ ] Operator Arrays are often abused. Range violations are common. Negative indices or indices greater than the maximum cause programs to access wrong data. [ ] We can create an array class that overloads [ ], and checks array bounds: class vect { public: vect(int n) : size(n) { p = new int[size]; assert(p!=NULL); for (int i=0;i<size;i++) { p[i] = 0; } ~vect() {delete [] p;} &[] int& operator[](int i) { assert((i>=0) && (i<size)); return p[i]; } private: int *p; int size; }; returns p[i] itself! Returning a reference to p[i] does not return a copy of p[i], but returns p[i] itself!

13 Operator Overloading int &int Why does operator[] return an int & rather than an int? vect v(10); int i; v[0] i = v[0]; // read the value at v[0]; v[0]write to v[0]! v[0] = 3; // write to v[0]! we return a reference // we return a reference so we can alter the value // so we can alter the value left hand side Functions that return references can appear on the left hand side of an assignment statement!

14 Operator Overloading We have seen several examples of how operators can be overloaded – but this is not the whole story. a  b  +, - a  b //where  is an operator +, -, etc is replaced by the compiler with: a.operator  (b) and it then looks to see whether you have written this particular member function. thislhsbrhs 'this' becomes the lhs and b the rhs.

15 Operator Overloading It also checks the 'type' of b - so operator  can be overloaded. a.operator  (b) If it cannot find any member function that matches, it replaces the text with: operator  (a,b) non-member function A non-member function, with two arguments, and tries again to find a match in the functions you have defined. You may choose to use either way. 1 2

16 Operator Overloading We are not allowed to overload operators for the standard types int int operator+(int i, int j) will not work. This leads to some difficulties. Suppose we have a clock class, and want to be able to say: clock a,b,c; c = a + b; This works if we have either a member function of clock operator+ clock clock::operator+(clock y); non-member function: or a non-member function: operator+ clock operator+(clock x, clock y);

17 Operator Overloading Suppose we also want to say: c = a + 10; This is ok if we have either operator+ clock clock::operator+(int i); operator+ or clock operator+(clock x, int i); What if we want to say: 10 c = 10 + a; Now we run in to difficulties. we are not allowed to treat 'int' as a class and overload its operators The compiler cannot convert this into a member function because we are not allowed to treat 'int' as a class and overload its operators. int::operator(clock x); is wrong!

18 Operator Overloading The compiler can only try to match: operator+ clock operator+(int i, clock x); We have lost symmetry. make them both non-member functions If we want to allow 10 + a as well as a + 10 then it is neater to make them both non-member functions. Non-member functions cannot access private data! friends We must either make them friends, (frowned on, perhaps) or provide functions to access the data – get() and set() routines, or whatever we want to call them (better but more work)

19 Operator Overloading Remember that some operators change the value of one of their arguments, and others do not. c++; adds one to the value of c the increment operator adds one to the value of c a + b not their sum operator+ does not change the value of either a or b, it returns their sum

20 Overloading I/O Operators cout << a; Can we overload the output operator? ostream Yes – but remember that the compiler first tries to find a member function of the ostream class (cout is an object of ostream), that accepts a clock object as a parameter cout.operator<<(a); The writer of the ostream class will not have included this function! And you cannot add it. non-member function Our only option is to supply the compiler with a non-member function to match operator<<(cout, a);

21 Operator Overloading class clock { clock(int seconds=0); friend ostream & operator<<(ostream &out, const clock &x); friend istream & operator>>(istream &in, clock &x);... unsigned long total; }; &operator<< ostream & operator<<(ostream &out, const clock &x) { int h, m, s; h = x.total / 3600; m = (x.total / 60) % 60; s = x.total % 60; out << h << “:” << m << “:” << s; return out; } Stream extraction (output) operator operator<< (also known as stream deletion operator) operator<< (also known as stream deletion operator) is usually called several times in a single statement. operator<< Consequently, the output of each call to operator<< cascades into the next call as input. That’s why it needs to return a reference to the output stream (cout). Note: operator precedence: left to right

22 Operator Overloading operator>> istream & operator>>(istream &in, clock &x) { int h, m, s; in >> h >> m >> s; in >> h >> m >> s; //input retrieved as h m s x.total x.total = h* m*60 + s; return in; } Stream insertion (input) operator

23 Operator Overloading Overloading the assignment operator. The copy constructor is called whenever we pass an object as an argument, pass an object as an argument, return an object, or return an object, or intialise an object with one of the same type intialise an object with one of the same type There is a need for a copy constructor because the default system copy constructor performs only shallow copy, and is not normally adequate when pointers are involved. Therefore, we need to perform a deep copy to copy what the pointers are pointing to.

24 Operator Overloading When we assign an object to another: str a, b; = a = b; NO copy constructor is involved NO copy constructor is involved. It is an assignment. If we want assignment to behave like a deep copy constructor, we need to overload the assignment operator. = str& str::operator=(const str &x){ delete[] s; s = new char[128]; strcpy(s, x.s); *this return *this; } Rule of thumb: Any time a class needs explicit copy constructor defined an explicit copy constructor defined, assignment operator it also needs an assignment operator defined.

25 Argument Types Argument types. You may always pass objects as arguments – sometimes we really want to – but most times, if we do, they lead to very inefficient code. If you pass across an object a copy constructor will be called. pass a reference to an object Instead of passing an object – most of the time we pass a reference to an object instead. Only a pointer is copied! However, passing a reference is not normally acceptable. If the actual argument to a function is a constant, then the compiler will not let you pass it to a reference parameter – the function may try to change the value of a constant!

26 Argument Types constreference The answer is to pass a 'const' reference parameter. Now the compiler can check that the function does not change its value (it will complain if it does try to) and constant can safely be passed in the knowledge that they can't be changed. Passing a is more efficient than passing an. Passing a const reference is more efficient than passing an object.

27 Return Types void These are again quite complicated. It is tempting to think that the assignment operator does not 'return' anything and so it should be void void str::operator=(str x) However this is NOT correct. It is perfectly correct to write a = b = c; which is the same as: a = (b = c); (b = c) has the 'value' of a. operator= reference to an str object operator= must return an str object. Or to make it more efficient a reference to an str object. Associativity of assignment operator: Right

28 Return Types Should it return a const reference? Well surprisingly no! We may want to stop anyone from writing: (a = b) = c; is legal but strangely enough this is legal for integers! (i = 3) (i = 3) = 2; first it assigns 3 to i and then assigns 2 to i And if we can do it with integers we should be allowed to do it with strings.

29 Return Types There was one final blunder when we overloaded the assignment operator for strings! a = a; a = a; Isn't very sensible, but it is legal. A program that uses our str class will fail if this statement occurs. We must modify our function as follows: str & str::operator=(const str &x){ if (&x == this) { return *this; return *this; } delete[] s; s = new char[128]; strcpy(s,x.s); return *this; } Allows multiple assignment with right-to-left associativity to be defined

30 Overloading Assignment and Subscripting Operators Must be done as non-static member functions Usually involve a reference return type Common Characteristics

31 Return Types Be careful when returning reference types. Consider the case of the prefix ++ operator: operator++ clock& operator++(){ total++; return *this; } This is ok This is ok, and more efficient than returning a clock object (a constructor would be called!)

32 Return Types But in the case of the postfix ++ operator: clock& operator++(int) { clock temp = *this; total++; return temp; } wrong!temp no longer exists! This is wrong! We are returning a reference to temp, and temp no longer exists! For certain functions we must return an object, not a reference. const clock operator++(int) { clock temp = *this; total++; return temp; }

33

34

35 Return Types Postfix ++ is nearly always less efficient than prefix ++ for user defined classes. view Clock3.cpp To see demo: