Operator Overloading CMSC 202.

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
CMSC 202, Version 2/02 1 Operator Overloading Strong Suggestion: Go over the Array class example in Section 8.8 of your text. (You may ignore the Array.
Operator Overloading Fundamentals
1 Overloading Operators COSC 1567 C++ Programming Lecture 7.
Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
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++
Review of C++ Programming Part II Sheng-Fang Huang.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
CMSC 202 Lesson 12 Operator Overloading II. Warmup  Overload the + operator to add a Passenger to a Car: class Car { public: // some methods private:
1 Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Operator Overloading ~ and User Defined Conversions.
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.
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.
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 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.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
CS212: Object Oriented Analysis and Design Polymorphism (Using C++)
Operator Overloading.
Chapter 18 - C++ Operator Overloading
CSE1002 – Problem Solving with Object Oriented Programming
Yan Shi CS/SE 2630 Lecture Notes
Learning Objectives Pointers as dada members
Chapter 13: Overloading and Templates
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Object Oriented Programming COP3330 / CGS5409
Operator Overloading Part 2
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Chapter 15: Overloading and Templates
The dirty secrets of objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
Operator Overloading; String and Array Objects
Operator Overloading.
Advanced Program Design with C++
Operator Overloading; String and Array Objects
CMSC 202 Lesson 22 Templates I.
Overview of C++ Overloading
Friends, Overloaded Operators, and Arrays in Classes
Operator Overloading, Friends, and References
Operator Overloading.
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
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++
Engineering Problem Solving with C++ An Object Based Approach
Templates I CMSC 202.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
CMSC 202 Lesson 6 Functions II.
C++ data types.
Presentation transcript:

Operator Overloading CMSC 202

Let’s Take a Closer Look… // In Employee.h class Employee { public: void SetManager(const Manager& boss); private: Manager m_boss; }; // In Employee.cpp void Employee::SetManager(const Manager& boss) m_boss = boss; } // In main… Employee me; Manager boss; me.SetManager(boss); Does this work? If so, how???

Assignment Operator Compiler creates a default assignment operator Copies data member values Manager a ---------------- Name = “Bob” Manager a(“Bob”); Manager b; b = a; Manager b ---------------- Name = “Bob” Manager b ---------------- Name = “” Not the same Manager! Just have same data! Copy data

Other Operators? Does this work with other operators? Money a(2, 50); // 2.50 Money b(3, 20); // 3.20 Money c; c = a + b; Unfortunately, no… But…we can define it ourselves!

Review: Function Overloading void swap (int& a, int& b); void swap (double& a, double& b); void swap (Bob& a, Bob& b); Same (or similar) functionality for different types… Function signatures include Function name Parameter list (both number and types) Sidenote C++ compiler has a built-in function called “swap”

Closer Look at Operators… We could do… Money a(2, 50); // 2.50 Money b(3, 20); // 3.20 Money c; c = Add(a, b); // we write… Or…we can use Operator Overloading and do this: c = a + b; // we write…

How could this function be improved? Operator Overloading Define a function that overloads an operator to work for a new type Example: const Money operator+ (const Money& a, const Money& b) { return Money( a.GetDollars() + b.GetDollars(), a.GetCents() + b.GetCents()); } Function Name…essentially How could this function be improved? What’s going on here?

Notice: implicit object! Operator Overloading Can also be overloaded as member functions First object in statement becomes the “calling” object a + b is equivalent to a.operator+(b) Example: const Money Money::operator+ (const Money& b) const { return Money( m_dollars + b.m_dollars, m_cents + b.m_cents); } One parameter! Why const? Notice: implicit object!

Evaluates to an unnamed object if we don’t return by const! Return by const value? const Money operator+ (const Money& a, const Money& b); const Money operator+ (const Money& b) const; Why return by const value? Imagine this Money a( 4, 50 ); Money b( 3, 25 ); Money c( 2, 10 ); (a + b) = c; Why is this an issue? Think about: Money d; d = (a + b) = c; What is this supposed to mean? (d gets c’s value) Return by const value prevents us from altering the returned value… Evaluates to an unnamed object if we don’t return by const!

Why not return by const-ref? const Money operator+ (const Money& a, const Money& b) { return Money( a.GetDollars() + b.GetDollars(), a.GetCents() + b.GetCents()); } Look closely… We return a copy of a temporary Money object… It goes out of scope when the function returns! [Q: Has return-by-ref been covered earlier?? Also, is above supposed to be an example of return-by-ref? (It isn’t, as-is—fix?)

Tries to find an int constructor that accepts a Money parameter…uh oh! Operator Overloading What about the following: Money a( 3, 25 ); Money d = a + 10; What does the compiler do? Looks for a constructor for Money that takes 1 int parameter Uses that constructor to build a new Money object Calls the ‘+’ operator function/method Money d = 10 + a; class Money { public: Money( int dollars, int cents ); Money( int dollars ); // more methods private: int m_dollars; int m_cents; }; Tries to find an int constructor that accepts a Money parameter…uh oh!

Other Operators? You can overload just about anything, but you should be VERY careful… [ ] * multiplication, pointer dereference / division + addition, unary positive - substraction, unary negative ++ increment, pre and post -- decrement, pre and post = assignment <=, >=, <, >, ==, != comparisons … Many, many others…

Practice Let’s overload the multiplication on money… // In Money.h class Money { public: Money( int dollars, int cents ); int GetDollars(); int GetCents(); void SetDollars( int dollars ); void SetCents( int cents ); private: int m_dollars; int m_cents; }; // In main… Money m( 100, 00 ); m = m * 10; Let’s overload the multiplication on money… Ignore “roll-over” Member function? Non-member function?

Challenge Fix the multiplication operator so that it correctly accounts for rollover.

Challenge II Overload the + operator to add a Passenger to a Car: class Car { public: // some methods private: vector<Passenger> passengers; }; Why is overloading the + operator this way not such a good idea?

Recall Private/Public Any method or function from anywhere can access these Private Only class-methods can access these Is there a way to get around this? Yes!

In class implementation! Friends Have access to an object’s private methods and data Syntax: friend retType methodName(params); retType methodName(params) { /* code */ } In class declaration! In class implementation!

Friend vs. Non-friend Friend Non-friend Why would you want this? friend const Money operator+ (const Money& a, const Money& b); // in class const Money operator+ (const Money& a, const Money& b) { return Money( a.dollars + b.dollars, a.cents + b.cents); } Non-friend const Money operator+ (const Money& a, const Money& b); // NOT in class return Money( a.GetDollars() + b.GetDollars(), a.GetCents() + b.GetCents()); Why would you want this?

Input/Output Overload the insertion << and extraction >> operators Cannot be member functions (why?) Can be friends Because… Money m; cin >> m; cout << “My money: “ << m << endl; Is better than… m.Input(); cout << “My money: “; m.Output(); cout << endl;

Output – Insertion Operator << Non-friend ostream& operator<<( ostream& sout, const Money& money); // NOT in class const Money& money) { sout << “$” << money.GetDollars() << “.” << money.GetCents(); return sout; } Friend (don’t forget to add friend to the prototype!) friend ostream& operator<<( ostream& sout, const Money& money); // in class sout << “$” << money.dollars << “.” << money.cents;

Operator<< Notes… You should override << for all of your classes Do not include a closing endl (after all data…why?) Operator<< is not a member function Always return ostream& Why?

Input – Extraction Operator >> // Input money as X.XX // friend version… istream& operator>>(istream& sin, Money& money) { char dot; sin >> money.dollars >> dot >> money.cents; return sin; } How would you do this as a non-friend function?

Unary Operators Can we overload unary operators? Negation, Increment, Decrement? YES! Let’s look at two cases Negation Increment Pre and Post Example Money m1(3, 25); Money m2; m2 = - m1; ++m2; m1 = m2++;

Negation (member function) const Money operator- ( ) const; const Money Money::operator- ( ) const { Money result; result.m_dollars = -m_dollars; result.m_cents = -m_cents; return result; }

Pre Increment Money Money::operator++( void ) { // increment the cents ++m_cents; // adjust the dollars if necessary // return new Money object return Money( m_dollars, m_cents); }

Post Increment Money Money::operator++( int dummy ) { // make a copy of this Money object // before incrementing the cents Money result(m_dollars, m_cents); // now increment the cents ++m_cents; // code here to adjust the dollars // return the Money as it was before // the increment return result; }

Restrictions Can’t overload every operator Can’t make up operators Can’t overload for primitive types Like operator<< for integers… Can’t change precedence Can’t change associativity Like making (-m) be (m-)

Good Programming Practices Overload to mimic primitives Binary operators should Return const objects by value Be written as non-member functions Be written as non-friend functions Overload unary as member functions Always overload << As non-friend if possible Overload operator= if using dynamic memory

Practice Let’s overload the operator== for the Money class Should it be a member function? Should it be a friend? What should it return? What parameters should it have? What do we need to do inside?

Challenge Overload the operator+= for a Money object Should it be a member function? Should it be a friend? What should it return? What parameters should it have? What do we need to do inside?