Operator overloading II

Slides:



Advertisements
Similar presentations
Operator overloading. Operatorsand precedence zLeft to right associative y:: scope resolution y. direct member access y-> indirect member access y[] subscripting.
Advertisements

1 Overloading Operators COSC 1567 C++ Programming Lecture 7.
Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
Class and Objects.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
 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 15: Operator Overloading
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.
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.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Object Oriented Programming in C++ Chapter5 Operator Overloading.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
1 Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
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.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator Overloads Part2. Issue Provide member +(int) operator Rational + int OK int + Rational Error.
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.
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+
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.
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.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 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:
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.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
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. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
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.
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.
11 Introduction to Object Oriented Programming (Continued) Cats.
Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing
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.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
Operator Overloading.
Andy Wang Object Oriented Programming in C++ COP 3330
CSE1002 – Problem Solving with Object Oriented Programming
Operator Overloading CS 3370 – C++ Chapter 14.
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
Overloading Operator MySting Example
Object-Oriented Programming (OOP) Lecture No. 21
Computer Programming FAST-NU FSB-CH Campus
Operator Overloading; String and Array Objects
Advanced Program Design with C++
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
Operator Overloading I
Operator Overloading; String and Array Objects
Presentation transcript:

Operator overloading II Output, input and other operators

‘this’ example bool Employee::operator>(const Employee& e) const { return(this->seniority > e->seniority); } called from the program like this: if (emp1 > emp2) emp1 accounts for ‘this’, emp2 becomes e

example without ‘this’ bool Employee::operator>(const Employee& e) const { return(seniority > e->seniority); } called from the program like this: if (emp1 > emp2) ‘this’ is more self-documenting, but more verbose

Invoking objects If the operator is binary but there is only one explicit argument, the ‘invoking instance’ is assumed to be the one on the left hand side of the expression. Class Date { public: // member functions Date& operator=(const Date&); }; void assign(Date& s1, Date& s2) s1 = s2; // instead of s1.operator=(s2); }

Overloading output operators iostream.h defines the cout object as an instance of the ostream class. The iostream.h file overloads << with functions handling each of the native data types. Example: ostream& operator<<(ostream& out, int n);

operator<< overloading ostream& operator<<(ostream& out, int n); This is a non-member function (not called as part of a particular class) therefore it needs two arguments (not one like member function operators) It returns an ostream so that it will work in multiple call settings. cout << int1 << int2; //see last lecture for details on chaining problems.

Advantages Rather than Clerk.showData(); we can do the following: cout << Clerk;

Problems If operator<< is a non-member function, 1. What does it look like? 2. How can it work on private data members of an Employee object?

What the non-member function looks like ostream& operator<<(ostream& out, const Employee& emp) { out << “Employee number is “ << emp.idNum; out << “ Salary is “ << emp.salary << endl; return(out) } a non-member function (not tied to any class)

How it can access private data To do this we must place the prototype of the non-member function in the public section of the class definition. Then, we must identify it as a ‘friend’ of the class. A ‘friend function’ has direct access to the private data members.

The original employee class class Employee { private: int idNum; double salary; public: Employee(const int id, const double salary); double addTwo(const Employee& emp); double operator+(const Employee& emp); }

Non-member functions can have access to private data class Employee { private: int idNum; double salary; public: Employee(const int id, const double salary); double addTwo(const Employee& emp); double operator+(const Employee& emp); friend ostream& operator << (ostream &out, const Employee& emp); // the prototype for a friend function }

Overloading input >> You can construct an overloaded extraction operator in a manner similar to that used for the insertion operator << One additional feature could be implemented as well, you could screen for invalid data as it was entered. This would also need to be a friend function if it was not a non-member of the class.

Extraction operator >> istream& operator>>(istream& in, Employee& emp) { cout << endl; // to clear the buffer cout << “Enter the employee id number “; in >> emp.idNum; cout << “Enter the salary “; in >> emp.salary; // data verification here return(in) } to use it from client code: cin >> Clerk;

Overloading ++ and -- It makes a big difference whether you are overloading the prefix (++i) or the postfix (i++) versions of this operator. Prefix makes the change, then processes the variable. Postfix processes the variable, then makes the change.

Overloaded prefix ++ Class Inventory { private: int stockNum; int numSold; public: Inventory(const int stknum, const int sold); friend ostream& out, const Inventory& item); Inventory* operator++(); } Inventory& Inventory::operator++() ++numsold; // or ++this->numsold; return(*this);

Use of the prefix ++ Inventory someItem(789, 84); // the stockNum is 789 // the numSold is 84 ++someItem; cout << someItem; // output says 85 items sold

Problem The definition of the prefix operator is easy enough. It increments the value before any other operation. But how will C++ be able to tell the difference between a prefix ++ operator and a postfix ++ operator Answer: overloaded postfix operators take a dummy argument.

Postfix operator dummy argument Inventory& Inventory::operator++() // prefix version { ++numsold; // or ++this->numsold; return(*this); } Inventory& Inventory::operator++(int) // postfix version numsold++; // or this->numsold++; dummy argument

Example of member functions for Fraction class // the prototype in the class definition Fraction& operator++(); // prefix Fraction& operator++(int); // postfix Fraction& Fraction::operator++() { numerator = numerator + denominator; return(*this); } Fraction& Fraction::operator++(int n)

Overloading relational operators (==) // the prototype in the class definition int operator==(Fraction const& f2); int Fraction::operator==(Fraction& f2) { if (numerator == f2.numerator && denominator == f2.denominator) return(1); else return(0); }

Assignment operator= Similar to the copy constructor, but Re-initializes already constructed objects Date today; // copy constructor ... today = “9/20/1999”; Need assignment operator accepting char*

Assignment operator Class Date { Date& operator=(const char* dCptr); ... } Date::operator=(const char* dCptr) { // parse dateCptr into m, d, y assign(m, d, y);

Assignment operator Compiler generates a default assignment operator if you do not define one bitwise copy only (‘shallow copy’) If you have dynamically allocated memory in your objects then you will need to write an assignment operator to create ‘deep copies’

Assignment operator Bitwise copy ok for classes like Date members of simple types only no pointers, therefore no remote ownership What happens if we bitwise copy an object owning a resource? Same problem as with default copy constructors

Assignment Declaration class Set { public: //Constructors... Set& operator=(const Set &s); private: int *data; int size; };

Set& Set::operator=(const Set &s) { if (this != &s) // no assignment to self if (data != 0) delete [] data; size = s.size; data = new int[size]; for (int i=0; i<size; ++i) data[i] = s.data[i]; } return *this;

Overloading restrictions At least one of the arguments to an overloaded operator MUST be an instance of the class to which the operator belongs. Class Date { public: // member functions Date operator+(const Date&); // OK! Date operator+(); // OK, due to ‘this’ }; // non-member functions friend Date operator+(int, int); // ERROR, no Dates friend Date operator-(int, const Date&); // OK

Overloading unary operators If the unary operator is a member function, then Empty argument list (no explicit arguments) Single argument passed implicitly (this) If the unary operator is not a member function than there will be one argument

Subscript operator[] Defines array style syntax for accessing individual elements of “container” classes Usage examples Set s1; s1[0] = 5; int value = s1[0]; MUST be made a class member Implementation Example

class Set { public: //Constructors... int& operator[](const int index); private: int *data; int size; };

int& Set::operator[](const int index) { if (index < 0 || index >= size) return data[0]; return data[index]; }

class Set { public: //Constructors… int& operator[](const int index); private: friend ostream& operator<<(ostream &stream, const Set &s); };

ostream& operator<<(ostream &stream, const Set &s) { for (int i=0; i<s.size(); ++i) stream << s[i] << “ “; stream << endl; return stream; }

Const Version of operator[] Must also add a const version of [] Back to class definition int operator[](const int size) const

class Set { public: //Constructors... int& operator[](const int index); int operator[](const int index) const; private: int *data; int size; };

Operator[] Summary non-const object const object Set s; const Set s; assignment retrieval assignment retrieval s[0] = 5; cout << s[0]; s[0] = 5; cout << s[0]; non-const version of [] const version of [] may need lvalue, must return reference does not need lvalue -> no reference

Operators - Global or Member ? Choice impacts the usage of the type Decision based on how you think type will be used Addition (Operator+) for Set Operator+ for sets creates union of both arguments Assume we made it a member function

Addition (Operator+) Example Set s1, s2, s3; s3 = s1 + s2; s3 = s1 + 2; s3 = 2 + s1; Why not create a constructor that takes an integer as an argument. Then it would be implicitly converted and the + operator could be called. Good idea, but won’t work as a general rule ! Why not ? 2 = s1; // would then become legal

Better Solution - Global Make addition (operator+) a global function How many global operator functions needed ? Capture s1 + s2, s1 + 2, 2 + s1 For each global operator function, add the friend specifier to the class declaration How could I reduce it to 1 global op. function? Now use an implicit conversion ! C++ implicitly converts lhs arguments ONLY when it applies to a global operator function, NOT member functions, thus can do 2 + s1, not 2 = s1

Operators - Rules of thunb Member operator functions Ones that are required to be members ([]) Generally have a “=“ in them Global operators Generally, +, -, /, * Decision based on use !

Constructors as type conversions What is a constructor is passed a value it does not expect? It may promote it. MyType::MyType(AnotherType); MyType::MyType(const AnotherType&); implicitly convert AnotherType object into MyType object

Constructors as type conversions If an object of MyType is expected, but object of AnotherType is specified class string { string(int len); … }; string s1(“C”), s2(“++”); cout << s1 + 10 + s2; // equivalent to: cout << s1 + tempString(10) + s2;