Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing 2007-2008.

Slides:



Advertisements
Similar presentations
Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
Advertisements

 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.
1 Operator Overloading. 2 Syntax The general syntax is: [friend] returntype operator ( ) { ; }
Software Design and C++ Programming Lecture 4 Operator Overloading and Streamed I/O.
OOP Spring 2007 – Recitation 31 Object Oriented Programming Spring 2007 Recitation 3.
Lecture 4 OOP Course. 4. Operators Using constructors: String int main(){ String s1(“My String”); String s2(s1); String s3; s3=s1; } int main(){ String.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
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 in C++
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.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Operator Overloading ~ and User Defined Conversions.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator overloading II
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.
J. P. Cohoon and J. W. Davidson © 1997 McGraw-Hill, Inc. Templates Generic functions and 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.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
 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.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
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.
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;
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
1 Object-Oriented Programming Using C++ A tutorial for pointers.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Operator Overloading Chapter Objectives You will be able to Add overloaded operators, such as +,-, *, and / to your classes. Understand and use.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CSCI-383 Object-Oriented Programming & Design Lecture 11.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
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 
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Operator Overloading CS 3370 – C++ Chapter 14.
Overloading C++ supports the concept of overloading Two main types
Pointers and Dynamic Arrays
Polymorphism in C++ Operator Overloading
Jim Fawcett Copyright ©
תכנות מכוון עצמים ו- C++ יחידה 06 העמסת אופרטורים
Overview of C++ Overloading
Object-Oriented Programming (OOP) Lecture No. 20
C++ Pointers and Strings
COP 3330 Object-oriented Programming in C++
C++ Templates L03 - Iterator 10 – Iterator.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
C++ Pointers and Strings
Jim Fawcett Copyright ©
Presentation transcript:

Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing

Operator Overloading Operator overloading is a more elegant way of making function calls. Syntactically different from function calls. The parameters do not appear inside parenthesis, but next to operator characters. Everything you do with operator overloading you can do with regular function calls. Example: t = x+y*z ; Here we have three binary operators called =, +, *

Operator Overloading - Syntax It is defined as is the operator The number of parameters depend: Class member operator functions: Binary operators have one parameter Unary operators have zero parameter Global operator functions: Binary operators have two parameters Unary operators have one parameter Example: x = y ; // x.opearator=(y) or operator=(x,y) ! x ;// x.operator!() or operator!(x)

Operator Overloading - Example #include using namespace std; class Integer { private:int i; public:Integer(int ii) : i(ii) {} const Integer operator+(const Integer& rv) const {cout << "operator+" << endl; return Integer(i + rv.i);} Integer& operator+=(const Integer& rv) {cout << "operator+=" << endl; i += rv.i; return *this; } }; int main() { cout << "built-in types:" << endl; int i = 1, j = 2, k = 3; k += i + j; cout << "user-defined types:" << endl; Integer ii(1), jj(2), kk(3); kk += ii + jj; }

Unary Operators + X - X ~X &X !X ++X X++ --X X--

Unary Operators – As Global Functions #include using namespace std; class Integer { long i; Integer* This() { return this; } public: Integer(long ll = 0) : i(ll) {} friend const Integer& operator+(const Integer& a); friend const Integer operator-(const Integer& a); friend const Integer operator~(const Integer& a); friend Integer* operator&(Integer& a); friend int operator!(const Integer& a); // Prefix: friend const Integer& operator++(Integer& a); friend const Integer& operator--(Integer& a); // Postfix: friend const Integer operator++(Integer& a, int); friend const Integer operator--(Integer& a, int); };

Unary Operators – As Global Functions // Global operators: const Integer& operator+(const Integer& a) { return a; } const Integer operator-(const Integer& a) { return Integer(-a.i); } const Integer operator~(const Integer& a) { return Integer(~a.i); } Integer* operator&( Integer& a) { return a.This(); } int operator!(const Integer& a) { return !a.i; } // Prefix: const Integer& operator++(Integer& a) { a.i++; return a; } const Integer& operator--(Integer& a) { a.i--; return a; } // Postfix: const Integer operator++(Integer& a, int) { Integer before(a.i); a.i++; return before; } const Integer operator--(Integer& a, int) { Integer before(a.i); a.i--; return before; }

Unary Operators – As Member Functions class Byte { unsigned char b; public: Byte(unsigned char bb = 0) : b(bb) {} const Byte& operator+() const { return *this; } const Byte operator-() const { return Byte(-b); } const Byte operator~() const { return Byte(~b); } Byte operator!() const { return Byte(!b); } Byte* operator&() { return this; } // Prefix const Byte& operator++() { ++b; return *this; } const Byte& operator--() { --b; return *this; } // Postfix const Byte operator++(int) { Byte before(b); b++; return before; } const Byte operator--(int) { Byte before(b); --b; return before; } };

Binary Operators – As Global Functions class Integer { long i; public: Integer(long ll = 0) : i(ll) {} // Operators: + - * / % ^ & | > friend const Integer operator+ (const Integer& left, const Integer& right); // Operators: += -= *= /= %= ^= &= |= >>= <<= friend Integer& operator+= ( Integer& left, const Integer& right); // Operators: == != = && || friend int operator== (const Integer& left, const Integer& right); } // In CPP const Integer operator+ (const Integer& left, const Integer& right) { return Integer(left.i + right.i); } Integer& operator+=(Integer& left, const Integer& right) { left.i += right.i; return left; } int operator==(const Integer& left, const Integer& right) { return left.i == right.i; }

Binary Operators – As Global Functions class Byte { unsigned char b; public: Byte(unsigned char bb = 0) : b(bb) {} // Operators: + - * / % ^ & | > const Byte operator+(const Byte& right) const { return Byte(b + right.b); } // Operator = only can be a member function Byte& operator=(const Byte& right) { if(this == &right) return *this; b = right.b; return *this; } // Operators: += -= *= /= %= ^= &= |= >>= <<= Byte& operator+=(const Byte& right) { b += right.b; return *this; } // Conditional operators return true/false: // Operators: == != = && || int operator==(const Byte& right) const { return b == right.b; } };

Unary ++ and -- Operators ++ and – – operators present may appear as Prefix : Before the variable : ++a Postfix : After the variable : a— When the compiler sees pre-increment/decrement : ++a : Compiler generates a call to operator++(a) or a.operator++() post-increment/decrement : a– Compiler generates a call to operator++(a, int) or a.operator++(int)

Arguments and Return Values For any argument that will not be changed Pass a const reference, for example in binary +, or < For a member function make it a const member function. ( Not with += or = ) Return value (might be anything). Return value may be a new value. (operator+ returns const value) Assignment operators modify the lvalue. They may be modified in chain. So they must return non-const reference. Logical operators must return an int (or bool) Return value optimization return Integer(left.i + right.i) Instead of Integer tmp(left.i + right.i); return tmp;

Comma Operator Operator Comma (,) is called when it is written explicitly to a list of values (not in a function call) #include using namespace std; class After { public: const After& operator,(const After&) const { cout << "After::operator,()" << endl; return *this; } }; class Before { }; Before& operator,(int, Before& b) { cout << "Before::operator,()" << endl; return b; } int main() { After a, b; a, b; // Operator comma called Before c; 1, c; // Operator comma called }

Operator –> Pointer Dereference Generally used when you want to make an object appear to be a pointer. (Like smart pointers, auto pointers) A pointer dereference operator must be a member function. It must return an object (or reference to an object) that also has a pointer dereference operator, or a pointer.

Operator –> Example class AutoPtr { private: Integer* myPtr; public: AutoPtr(Integer *ptr=0) : myPtr(ptr) { } AutoPtr(AutoPtr& right) : myPtr(right.release()) { } AutoPtr& operator=(AutoPtr& right) { reset(right.release()); return (*this); } ~AutoPtr(){ delete myPtr; } Integer& operator*() const { return (*get()); } Integer* operator->() const { return (get()); } Integer* get() const { return (myPtr); } Integer* release() { Integer* tmp = myPtr; myPtr = 0 ; return (tmp); } void reset(Integer* ptr = 0) { if (ptr != myPtr) delete myPtr; myPtr = ptr; } };

Non-member operators Global operator functions can have different argument types. operator[] gets an integer the index of the aggregate #include using namespace std; class IntArray { enum { sz = 5 }; int i[sz]; public: IntArray() { memset(i, 0, sz* sizeof(*i)); } int& operator[](int x) { return i[x]; } friend ostream& operator<<(ostream& os, const IntArray& ia); friend istream& operator>>(istream& is, IntArray& ia); }; ostream& operator<<(ostream& os, const IntArray& ia) { for(int j = 0; j < ia.sz; j++) { os << ia.i[j]; if(j != ia.sz -1) os << ", "; } os << endl; return os; } istream& operator>>(istream& is, IntArray& ia) { for(int j = 0; j < ia.sz; j++) is >> ia.i[j]; return is; }

Examples 1. Define a String class 1. With + and += operators 2. Copy constructor and operator= 3. Try to define it with Reference count 2. IntArray: 1. Define class IntArray a dynamic integer array. 2. Define operator= 3. Define operator+ and += meaning that the elements are added to the end 4. Define operator[] and operators << with ostream. 5. Define ++/-- meaning that to every element a 1/-1 is added 3. Smart Pointer 1. Define class Integer and add function getValue() 2. Define class SmartIntegerPointer that keeps a pointer to Integer 4. Smart Pointer with Reference Count Try to solve 2 with not re-creating new pointers in every copying.