OOP Egar 2008 – Recitation 41 Object Oriented Programming Spring 2006 Recitation 6.

Slides:



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

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.
CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Operator Overloading Fundamentals
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
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 ( ) { ; }
OOP Spring 2007 – Recitation 31 Object Oriented Programming Spring 2007 Recitation 3.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
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),
Operator overloading Object Oriented Programming.
Operator Overloading in C++
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.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
OPERATOR OVERLOADING. Closely related to function overloading is - operator overloading. In C++ you can overload most operators so that they perform special.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
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.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
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.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
CSC241 Object-Oriented Programming (OOP) Lecture No. 8.
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 Understand Operator Overloading and how it is implemented in C++ ? | Website for students | VTU NOTES.
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.
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
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;
CS212: Object Oriented Analysis and Design Lecture 11: Operator Overloading-I.
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 CSC241: Object Oriented Programming Lecture No 08.
Operator Overloading.
Chapter 18 - C++ Operator Overloading
Object-Oriented Programming (OOP) Lecture No. 16
CSE1002 – Problem Solving with Object Oriented Programming
Operator Overloading Introduction
Yan Shi CS/SE 2630 Lecture Notes
Operator Overloading; String and Array Objects
C# Operator Overloading and Type Conversions
Motivation and Overview
Object-Oriented Programming (OOP) Lecture No. 21
Object-Oriented Programming (OOP) Lecture No. 16
Operator Overloading BCA Sem III K.I.R.A.S.
Chapter 14: More About Classes.
Operators Lecture 10 Fri, Feb 8, 2008.
Operator Overloading; String and Array Objects
Operator Overloading; String and Array Objects
Abstraction: Generic Programming, pt. 2
Operator Overloading, Friends, and References
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++
Operator Overloading I
Operator Overloading; String and Array Objects
Presentation transcript:

OOP Egar 2008 – Recitation 41 Object Oriented Programming Spring 2006 Recitation 6

OOP Egar 2008 – Recitation 42 Friends

OOP Egar 2008 – Recitation 43 Non-member Private Access Sometimes we need to “break” the encapsulation of a class – allow a non- member function access to private parts. For example, operator+() should not be a member function, but it might need access to implementation. C++ allows the class to declare some function as its friend, thus allowing access to private parts.

OOP Egar 2008 – Recitation 44 Friend Function Adding keyword friend before function name in a class definition implies that this function is friend of the class rather than member. The function still needs to be defined. class Complex { friend const Complex operator+(const Complex&, const Complex&); }; operator+() above is not a member function of Complex (we can’t call c.operator+() for Complex c ), but it can access private parts of Complex.

OOP Egar 2008 – Recitation 45 Friend Class A class can declare another class’s method as friend : class A { friend void B::stop(); }; class B { void stop(); }; If all methods of one class need to be friend s of another, the whole class can be declared friend : class A { friend class B; };

OOP Egar 2008 – Recitation 46 Technicalities friend ship is not transitive. A friend of a friend is not (necessarily) a friend. It doesn’t matter if the friend declaration is made in the public or private parts (public is better). If the friend function is itself a method of another class, it doesn’t matter if it is in the public or private parts. Don’t declare everything friend just because you can.

OOP Egar 2008 – Recitation 47 Operator Overloading

OOP Egar 2008 – Recitation 48 The “Old” Matrix Consider class Matrix that implements a 2D matrix of integers. It supports all the usual operations – arithmetics, printing, indexing, assigning. Its use looks like: Matrix m1, m2, m3; m3.copy(m1); m3.add(m2); m3.print(); cout << m1.index(5, 5);

OOP Egar 2008 – Recitation 49 The “New” Matrix It’s much more natural to use standard notation: +, *, <<, = … These are called operators, and in C++ the programmer can define new meanings for them – this is called operator overloading. Now the usage is more natural: Matrix m1, m2, m3; m3 = m1 + m2; cout << m3; cout << m1(5, 5);

OOP Egar 2008 – Recitation 410 Syntax An overloaded operator is simply a function with funny name and calling syntax. It can implement any behavior we want ( + can subtract, etc.) Name for the function that implements + is operator+() and it can be called either by m1 + m2; or by operator+(m1, m2); Basically, the compiler replaces the former form by the latter.

OOP Egar 2008 – Recitation 411 Two Forms of An Operator Just as any function, an operator can be defined as a non-member function, or as a class method. If a compiler sees m1 + m2; it looks for operator+ in m1 ’s class and writes m1.operator+(m2); and for non-member operator+ and writes operator+(m1, m2); If both exist, overloading resolution is used.

OOP Egar 2008 – Recitation 412 Binary and Unary A binary operator takes two arguments (such as +, -, < ). A unary operator takes one argument (such as ++, ! ).

OOP Egar 2008 – Recitation 413 Overloadable Binary These binary operators can be overloaded: +-*/% &|^ =+=-=*=/=%=<<=>>=&=|=^= <<=>>===!= []() ->*->, <<>>&&||

OOP Egar 2008 – Recitation 414 Overloadable Unary These unary operators can be overloaded: ~!-+ &*newnew[]deletedelete[] ++ (prefix)++ (postfix)-- (prefix)-- (postfix)

OOP Egar 2008 – Recitation 415 Non-overloadable These operators cannot be overloaded: ::..*sizeoftypeid?:

OOP Egar 2008 – Recitation 416 Binary Looks and Calling A binary operator can be defined by either –a non-static member function taking one argument of any type, –or a non-member function taking two arguments of any type. Return type can be anything. For a binary can be interpreted either as or as b).

OOP Egar 2008 – Recitation 417 Unary Looks and Calling A unary operator can be defined by either –a non-static member function taking no arguments, –or a non-member function taking one argument of any type. Return type can be anything. For a can be interpreted either as or as

OOP Egar 2008 – Recitation 418 Must-be Members These operators must be non-static member functions of a class: – operator= – operator[] – operator() – operator-> This is to ensure that their first operand is lvalue. All the rest can be either member or non- member.

OOP Egar 2008 – Recitation 419 Example Implementation Class TextNum

OOP Egar 2008 – Recitation 420 TextNum ’s Description Let’s implement a class that holds a text description of an integer. A TextNum can be printed, assigned to, added/multiplied (etc.), compared, incremented, negated, indexed, and more…

OOP Egar 2008 – Recitation 421 Basic Definition class TextNum { public: TextNum(int); TextNum(const TextNum&); int to_int() const; string to_string() const; private: string _textNum; int _num; string intToString(int); };

OOP Egar 2008 – Recitation 422 Binary Operator+() const TextNum operator+ (const TextNum& lhs, const TextNum& rhs) { return lhs.to_int() + rhs.to_int(); }

OOP Egar 2008 – Recitation 423 Commutativity and Implicit Conversions If operator+ is a member function, we have a problem: TextNum t1; int i; t1 + i;// FINE, means t1.operator+(i), i is // implicitly converted to TextNum i + t1;// ERROR, not int::operator+() nor // operator+(TextNum,TextNum) exist Making an operator a non-member function allows implicit type conversions on the first argument: t1 + i;// operator+(t1, i) i + t1;// operator+(i, t1) // both times i is implicitly // converted to TextNum

OOP Egar 2008 – Recitation 424 Operator==() bool operator== (const TextNum& lhs, const TextNum& rhs) { return lhs.to_int() == rhs.to_int(); }

OOP Egar 2008 – Recitation 425 Operator<<() ostream& operator<< (ostream& output, const TextNum& rhs) { output << rhs.to_string(); return output; }

OOP Egar 2008 – Recitation 426 Operator<<() as Non-member Shifting operator ( >>, << ) are commonly used in C++ for input/output operations. operator<<() need not be commutative, but still we declare it non-member. This is because otherwise it would have to be called like this: t1 << cout;// t1.operator<<(cout);

OOP Egar 2008 – Recitation 427 Unary Operator-() TextNum TextNum::operator-() { return -_num; }

OOP Egar 2008 – Recitation 428 Prefix and Postfix Operator++() // Prefix TextNum& TextNum::operator++() { _textNum = intToString(++_num); return *this; } // Postfix const TextNum TextNum::operator++(int) { TextNum old = *this; ++(*this); return old; }

OOP Egar 2008 – Recitation 429 Prefix and Postfix Unary operator++() and operator--() can be either prefix ( ++i ) or postfix ( i++ ). Overloaded postfix operator has a dummy int parameter that is not used. Prefix operator should return a reference to this, while postfix should return a const copy of the old state.

OOP Egar 2008 – Recitation 430 Operator=() and Operator+=() TextNum& TextNum::operator=(const TextNum& rhs) { _num = rhs._num; _textNum = rhs._textNum; return *this; } TextNum& TextNum::operator+=(const TextNum& rhs) { _num += rhs._num; _textNum = intToString(_num); return *this; }

OOP Egar 2008 – Recitation 431 Assignment operator=() is called assignment operator. If it is not defined for a class, compiler will automatically generate one (if needed). By a strange turn of fate, operator=() must be a member function, while operator+=(), etc. can be a non-member function. Assignment operators should return a reference to *this.

OOP Egar 2008 – Recitation 432 Assignment operator Make sure to return a reference to the objects to allow chaining. May be weird (a=b)=c but this is how int works. MAKE SURE TO CHECK FOR SELF ASSIGNMENT! If your class using dynamic allocated data then obj=obj //KABOOM!!!

OOP Egar 2008 – Recitation 433 Operator[]() // non-const char& TextNum::operator[](size_t idx) { return _textNum[idx]; } // const const char& TextNum::operator[](size_t idx) const { return _textNum[idx]; }

OOP Egar 2008 – Recitation 434 Subscripting Operator[]() allows subscripting: t1[10] = 'M‘; Usually, both non- const and const versions should be provided – the former allows changing the contents, while the latter allows access when the object is const.

OOP Egar 2008 – Recitation 435 Operator()() const string TextNum::operator()(size_t start, size_t end) { return _textNum.substr(start, end-start+1); }

OOP Egar 2008 – Recitation 436 Function Call operator()() is called function call operator. cout << t1(0, 5); The above looks just like a call to a function named t1() with arguments 0 and 5. This allows creating functors – objects that act like functions. We will see their use in STL. operator()() can have any number of parameters. This allows subscripting with more that one index (useful in matrices, for example).

OOP Egar 2008 – Recitation 437 A Word of Warning Never overload &&, || or, This is because C++ employs short-circuit evaluation of boolean expressions: char *p; if ( (p!=0) && (strlen(p) > 5) ) … –If p is 0, strlen() is never called. But overloading changes the syntax to function call syntax, and in function call all parameters must be evaluated before the call.

OOP Egar 2008 – Recitation 438 Example TextNum Program TextNum t1(-1032), t2(32); cout << t1 << endl; cout << t1 + t2 << endl; ++t1; t2--; if (t1 < t2) { cout << t1 << " is less than " << t2 << endl; } else { cout << t1 << " is more than " << t2 << endl; } cout << 'Z' << (t1 + t )(1,3) << endl;

OOP Egar 2008 – Recitation 439 Output minus one thousand thirty two minus one thousand minus one thousand thirty one is less than thirty one Zero

OOP Egar 2008 – Recitation 440 More on operator overloading Here: lite/operator-overloading.htmlhttp:// lite/operator-overloading.html