Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:

Slides:



Advertisements
Similar presentations
Operator Overloading Fundamentals
Advertisements

Class and Objects.
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.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
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 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 in C++
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.
OPERATOR OVERLOADING. Closely related to function overloading is - operator overloading. In C++ you can overload most operators so that they perform special.
Object Oriented Programming in C++ Chapter5 Operator Overloading.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
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:
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Case Study - Fractions Timothy Budd Oregon State University.
Introduction to Classes in C++
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Operator Overloads Part2. Issue Provide member +(int) operator Rational + int OK int + Rational Error.
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+
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Chapter 8 Operator Overloading, Friends, and References.
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.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
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 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
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;
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
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.
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345.
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.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Dale Roberts 1 Operator Overloading Member Functions Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
COMP 3000 Object-Oriented Programming for Engineers and Scientists Operator Overloading Dr. Xiao Qin Auburn University
Object Oriented Programming COP3330 / CGS5409.  Arithmetic Operator Overloading  Increment (++) / Decrement (--)  In-class exercise.
Andy Wang Object Oriented Programming in C++ COP 3330
CSE1002 – Problem Solving with Object Oriented Programming
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.
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
Object Oriented Programming COP3330 / CGS5409
Operator Overloading; String and Array Objects
Operator Overloading.
Advanced Program Design with C++
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
Operator Overloading; String and Array Objects
Presentation transcript:

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9: Operator overloading Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Sometimes using methods to implement arithmetic-style operations is not very convenient. Let us take as an example a Rational class: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ class Rational { public: Rational(int = 0, int = 1); //default constructor Rational(const Rational & r); //copy constructor int numerator; // numerator of fraction int denominator; // denominator of fraction };

Concordia University Department of Computer Science and Software Engineering To implement the addition of two Rational objects, the following method could be added: Such a method would require that we add three Rational numbers in the following awkward manner: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ const Rational Rational::add(const Rational& r) const { int n = numerator * r.denominator + denominator * r.numerator; int d = denominator * r.denominator; return Rational(n, d); } Rational a(5, 6); Rational b(2, 3); Rational c(1, 2); Rational d = a.add(b.add(c));

Concordia University Department of Computer Science and Software Engineering Since the addition operation has an arithmetic flavor to it, it would make much more sense if we could write: C++ provides a very convenient way to implement arithmetic- style operators: operator overloading. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ Rational d = a + b + c; Rational Rational::operator+(const Rational& a) const { Rational sum; sum.numerator = a.numerator * denominator + a.denominator * numerator; sum.denominator = a.denominator * denominator; return sum; }

Concordia University Department of Computer Science and Software Engineering Operator overloading allows existing C++ operators to work with user-defined data types. Limitations: At least one operand must be a user-defined type, i.e. it is impossible to change the meaning of an operator applied to a basic type such as int. Restricted to a fixed set of operators. Cannot change precedence and associativity of operators. Should not change the meaning of an operator, e.g. operator+ should always do something similar to addition. Otherwise it would be confusing. Operator overloading Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering + - * / % ^ & | ~ ! && || >, < >= = += -= *= /= %= &= |= ^= >= [ ]( ) -> ->* new delete Operator overloading Joey Paquet, COMP Advanced Program Design with C++ Operators that can be overloaded:

Concordia University Department of Computer Science and Software Engineering Operators can be overloaded either as member functions or as free operators. Unary operators can be members with no parameter or free operators with one parameter: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ // unary minus member operator const Rational Rational::operator-() const { Rational minus; minus.numerator = -(this->numerator); minus.denominator = this->denominator; return minus; } // unary minus free operator const Rational operator-(Rational& a) { Rational minus; minus.numerator = -(a.numerator); minus.denominator = a.denominator; return minus; }

Concordia University Department of Computer Science and Software Engineering Binary operators can be members with one parameter or free operators with two parameters: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ // binary operator+ as free operator const Rational operator+(Rational& a, Rational& b) { Rational sum; sum.numerator = a.numerator * b.denominator + a.denominator * b.numerator; sum.denominator = a.denominator * b.denominator; return sum; } // binary operator+ as member operator const Rational Rational::operator+(const Rational& a) const { Rational sum; sum.numerator = a.numerator * this->denominator + a.denominator * this->numerator; sum.denominator = a.denominator * this->denominator; return sum; }

Concordia University Department of Computer Science and Software Engineering The result of operators should be a new value returned by the operator, which should be constant, so that the result cannot be the target of an assignment: Parameters should be passed by value or preferably by constant reference, as the operands should not be modified by the operations. Member operators should be declared as constant to signify that the operation does not alter the calling object. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ Rational r1(1,2), r2(2,3), r3(0,1); (r1 + r2) = r3; //should not be allowed! const Rational Rational::operator+(const Rational& a) const

Concordia University Department of Computer Science and Software Engineering Increment/decrement operators overloading Prefix: increments and then returns value Postfix: increments but returns original value. Note: postfix operator uses a dummy int parameter Operator overloading Joey Paquet, COMP Advanced Program Design with C++ // prefix increment operator Rational& Rational::operator++(){ numerator = numerator + denominator; return *this; } // postfix increment operator Rational Rational::operator++(int){ Rational temp = *this; numerator = numerator + denominator; return temp; }

Concordia University Department of Computer Science and Software Engineering Stream input/output operators overloading. Must be overloaded as free operators. Uses the stream input/output operators to input/output individual values of the data members. Returns the stream as a reference so that it can then be used sequentially, e.g. : Operator overloading Joey Paquet, COMP Advanced Program Design with C++ ostream& operator<<(ostream &output, const Rational &r) { output << r.numerator << "/" << r.denominator; return output; } istream& operator>>(istream &input, Rational &r) { input >> r.numerator >> r.denominator; return input; } cout << ++a << endl << b++ << endl << b << endl;

Concordia University Department of Computer Science and Software Engineering Can implement casting operators: Will be called implicitly by the compiler when necessary, e.g. : Or when an explicit cast is made, e.g. : Note that the casting operator has very high precedence: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ Rational::operator double(){ return numerator / (double)denominator; } Rational b(2, 3); float f = b; //casting operator implicitly called cout << b++ << endl << b << endl << (float)b << endl;

Concordia University Department of Computer Science and Software Engineering Overloading the assignment operator: The assignment operator returns a reference to its result, so that a cascade of assignments is possible. If an assignment operator is not provided, the compiler will generate one automatically, which will do a member-wise shallow copy. If no data members are pointers, an assignment operator does not need to be explicitly overloaded. If the class contains pointer members, the assignment operator must be explicitly overloaded, or else it will be only copying the pointer values. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ const Rational& Rational::operator=(const Rational& r){ numerator = r.numerator; denominator = r.denominator; return *this; }

Concordia University Department of Computer Science and Software Engineering Let us imagine that numerator and denominator are int*, then we may have the following assignment operator: This would in fact create a memory leak, as the memory previously reserved to numerator and denominator has not been deleted. So what we need seems to be the following: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ const Rational& Rational::operator=(const Rational& r){ numerator = new int (r.numerator); denominator = new int (r.denominator); return *this; } const Rational& Rational::operator=(const Rational& r){ delete numerator; delete denominator; numerator = new int (r.numerator); denominator = new int (r.denominator); return *this; }

Concordia University Department of Computer Science and Software Engineering But then let us imagine that we do a self-assignment, e.g. : This would in fact lead us to delete the memory allocated to the pointers first, and then try to copy their value, which would fail. So we also need to do a self-assignment check: Operator overloading Joey Paquet, COMP Advanced Program Design with C++ const Rational& Rational::operator=(const Rational& r){ if (&r != this){ delete numerator; delete denominator; numerator = new int (r.numerator); denominator = new int (r.denominator); } return *this; } Rational a(5, 6); a = a;

Concordia University Department of Computer Science and Software Engineering There are some problems with the use of member operators. For example, what if we want to do the following (legitimate) operation: This requires the operator+ to be overloaded in the Rational class again, but this time taking a parameter of type int. However, this does not entirely solve the problem, as we might want to do: In this case, what would be needed is to overload the operator+ for int that would take a parameter of type Rational. Unfortunately, we cannot do that. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ Rational a(5, 6); Rational c = a + 25; Rational a(5, 6); Rational c = 25 + a;

Concordia University Department of Computer Science and Software Engineering So the best solution is to define our operators as free operators. This way, we can overload them with any operand type we need, as both of the operands are explicitly mentioned. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ // operator+ as free operator const Rational operator+(const Rational& a, const Rational& b) { Rational sum; sum.numerator = a.numerator * b.denominator + a.denominator * b.numerator; sum.denominator = a.denominator * b.denominator; return sum; } // operator+ as free operator const Rational operator+(const Rational& a, const int& b_int) { Rational sum, b(b_int,1); sum.numerator = a.numerator * b.denominator + a.denominator * b.numerator; sum.denominator = a.denominator * b.denominator; return sum; } // operator+ as free operator const Rational operator+(const int& a_int, const Rational& b) { Rational sum, a(a_int,1); sum.numerator = a.numerator * b.denominator + a.denominator * b.numerator; sum.denominator = a.denominator * b.denominator; return sum; }

Concordia University Department of Computer Science and Software Engineering Let us redefine our class so that the data members are now private, which is better practice: Then our three overloaded free operator+ don’t work anymore, as they cannot access the private members of the class Rational. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ class Rational { public: Rational(int = 0, int = 1); // default constructor Rational(const Rational & r); // copy constructor private: int numerator; // numerator of fraction int denominator; // denominator of fraction };

Concordia University Department of Computer Science and Software Engineering A solution would be to provide accessors for numerator and denominator, which is something that we may not want to do, as it would expose the data to the exterior. A better solution is to declare the free operators as friends to the Rational class. In fact, this is one of the most common use of friends. Operator overloading Joey Paquet, COMP Advanced Program Design with C++ class Rational { friend const Rational operator+(const Rational&, const Rational&); friend const Rational operator+(const Rational&, const int&); friend const Rational operator+(const int&, const Rational&); public: Rational(int = 0, int = 1); // default constructor Rational(const Rational & r); // copy constructor private: int numerator; // numerator of fraction int denominator; // denominator of fraction };

Concordia University Department of Computer Science and Software Engineering As member Defined as a member of the class. May use data members, as the operator is a member of the class. Operator belongs to the class (as opposed to non-member). Best from the point of view of OO principles, but… The calling object is the left operand of the operator, so thus this suffers from lack of type conversion of the left operand if it is a basic type. As non-member non-friend Defined as external to the class. Not related nor mentioned in the class, except by its operands type. Implementation code cannot refer to private members of its operands, thus necessitating accessors, which might not be desirable. Declares all operands and no calling object. May accommodate different types for all its operands. As friend Defined as external to the class, but introduced inside the class as a friend At least, it is mentioned in the class declaration, though it is not a member. As a friend, it may use private data members, thus does not necessitate accessors. Has two declared operands and no calling object. May have type conversion for both of its operands. Operator overloading Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Michigan Technical University. Operator overloading.Operator overloading Paul Deitel, Harvey Deitel. C++ How To Program. Prentice Hall, ISBN-13: Y. Daniel Liang. Introduction to Programming with C++. Chapter 14. Prentice Hall, ISBN-13: References Joey Paquet, COMP Advanced Program Design with C++