©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.

Slides:



Advertisements
Similar presentations
Operator Overloading Fundamentals
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 14 Operator Overloading: What does + mean? Consider the code below. Note the multiple uses of “+”. #include using namespace std; int main() { int.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
OOP Spring 2007 – Recitation 31 Object Oriented Programming Spring 2007 Recitation 3.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Chapter 13: Overloading.
Chapter 15: Operator Overloading
OOP Egar 2008 – Recitation 41 Object Oriented Programming Spring 2006 Recitation 6.
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.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
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.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
Operator Overloading and Type Conversions
OPERATOR OVERLOADING. Closely related to function overloading is - operator overloading. In C++ you can overload most operators so that they perform special.
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.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
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.
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.
CSC241 Object-Oriented Programming (OOP) Lecture No. 8.
Chapter 8 Operator Overloading, Friends, and References.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
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.
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. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
CONSTRUCTOR AND DESTRUCTORS
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.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
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.
1 CSC241: Object Oriented Programming Lecture No 08.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
Object Oriented Programming COP3330 / CGS5409.  Arithmetic Operator Overloading  Increment (++) / Decrement (--)  In-class exercise.
Operator Overloading.
Object-Oriented Programming (OOP) Lecture No. 16
CSE1002 – Problem Solving with Object Oriented Programming
Operator Overloading CS 3370 – C++ Chapter 14.
Operator Overloading Introduction
Overloading C++ supports the concept of overloading Two main types
Overloading Operator MySting Example
Object-Oriented Programming (OOP) Lecture No. 16
Chapter 15: Overloading and Templates
Operators Lecture 10 Fri, Feb 8, 2008.
Operator overloading Dr. Bhargavi Goswami
Operator Overloading.
Presentation transcript:

©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading

©Fraser Hutchinson & Cliff Green Why? Operator overloading provides no new capabilities in C++ –Semantic sugar –Provides conventional (and more convenient) notation for manipulating class objects –Often better presents class semantics (particularly for value classes)

©Fraser Hutchinson & Cliff Green Generic Programming and Operators However, operator overloading can be crucial in template functions and classes: template T sum (T x) { return (x < 1 ? 0 : x + sum(x-1)); } The above function treats class and built-in types equivalently (with the same syntax)

©Fraser Hutchinson & Cliff Green Traditional String Manipulation char const * str1 (“abc”); char const * str2 (“def”); char const * str3 (“ghi”); char full_string[64]; strcpy(full_string, str1); strcat(full_string, str2); strcat(full_string, str3); fprintf(“string is now ‘%s’.\n”, full_string); // outputs “string is now ‘abcdefghi’.”

©Fraser Hutchinson & Cliff Green Operators Overloaded std::string const str1 (“abc”); std::string const str2 (“def”); std::string const str3 (“ghi”); std::string full_string (str1); // copy ctor full_string += str2; // operator += overloaded full_string += str3); cout << “string is now ‘“ << full_string << ‘’.\n”; // outputs “string is now ‘abcdefghi’.”

©Fraser Hutchinson & Cliff Green ->, = Operators ‘pointer to’ operator T *tp = new class T; tp->myMethod(); // same as (*tp).myMethod(); Equality operator a == b; // overload needed for class types

©Fraser Hutchinson & Cliff Green Limitations Anything you can do with operators can be done via methods (reverse is not true) Some operators may not be overloaded Can only overload existing operators – new operators may not be defined Limited to syntax defined in the C++ grammar (explained in more detail later)

©Fraser Hutchinson & Cliff Green What Can be Overloaded ‘Normal’ Operators + - * / % & ^ | > < ! = ~+= -= *= /= %= &= ^= |= >= <= != == ~= && || >>= <<= ‘Special’ operators [] () -> ->*, > new, delete, new[], delete[]

©Fraser Hutchinson & Cliff Green What Cannot be Overloaded ::..* Scope resolution operator, as in namespace::identifier Member selection, as in T.member Member selection through pointer to member, as in T.*member These all take a name rather than a value as the second operand

©Fraser Hutchinson & Cliff Green Declaration returntype ‘operator’ symbol (parameters) Perhaps most common is the assignment operator T& operator= (T const &);

©Fraser Hutchinson & Cliff Green Binary Operators Non-static member function taking one argument class X { public: X & operator = (X const &); } The LHS is the object itself

©Fraser Hutchinson & Cliff Green Binary Operators Non-member function taking two arguments void operator + ( X a, X b ); This function has no special access to internals of class X For can be interpreted as (bb) or

©Fraser Hutchinson & Cliff Green Unary Operators Non-static member function taking no arguments class X { public: X & operator ++(); // prefix ++ }; Again, the LHS is the object itself can be interpreted as () or

©Fraser Hutchinson & Cliff Green Unary Operators Non-member function taking one argument void operator* (X& x); // deref op As with binary operators, this function has no special access to internals of class X

©Fraser Hutchinson & Cliff Green Member vs Non-Member Recommendations Method (member function): All unary operators Must be a method: = () [] -> Method: += -= /= *= ^= &= |= %= >>= <<= All other binary operators: Non-member (global) function

©Fraser Hutchinson & Cliff Green “Special” operators May be thought of as having no strongly predefined meaning For example: “Array” subscript operator, functor aids, memory allocation, conversion operators

©Fraser Hutchinson & Cliff Green Operator Details Most binary and unary operators can be either methods or global functions Method versions are applied to LHS of the expression (binary ops) or directly to object (unary ops) Example expression: x = y + 2; either a global or a member version works

©Fraser Hutchinson & Cliff Green Grammatical Coherence Operator “arity” cannot be changed class X { X operator/(); // err, not unary op X operator &(X,X); // err, not ternary }; X operator % (X); // err, not unary

©Fraser Hutchinson & Cliff Green Predefined Meanings Only a few assumptions are made operator= operator[] operator() operator-> Must be non-static member functions, are assured an L-value is possible

©Fraser Hutchinson & Cliff Green Redundant Operators and Pre- Defined Meanings Built-in type operator equivalences not carried over – for int : a++ means a+=1, means a=a+1 For class operator overloading, no equivalences: X operator++(int) // postfix version –does not automatically define X operator+= (int) Associativity and precedence cannot be changed from built-in grammar rules

©Fraser Hutchinson & Cliff Green Redundancy Given x = x + 2, x = 2 + x is NOT necessarily valid (transitivity is not assumed) Compiler cannot assume intent from operator semantics For example, two operators are needed: T operator+ (int left, T const& right ); T operator+ (T const& left, int right ); First version (left op is integer) can’t be method (since would require adding method to built-in type int )

©Fraser Hutchinson & Cliff Green Redundant Operators x = x + 1; x += 1; x++; ++x; Gives 5 possible operations – all must be overloaded for class (user-defined) types (although copy assignment might be compiler generated)

©Fraser Hutchinson & Cliff Green Operators and Class Types An operator function must be either a member function or take at least one argument of class (user-defined) type C++ not intended to be mutable - cannot change expression rules, but meanings in the context of a user-defined object can be defined Thus, operators cannot be defined that operate exclusively on pointers For member functions, the first operand must be a user-defined object

©Fraser Hutchinson & Cliff Green Operators in Namespaces namespace std { class ostream { ostream &operator << (char const *); }; extern ostream cout; typedef basic_string string; ostream & operator << (ostream &, string const &); } // end namespace std int main() { char const * p = “hello”; std::string s (“world”); std::cout << p << “, “ << s << endl; }

©Fraser Hutchinson & Cliff Green Actual Function Calls std::cout << p becomes std::cout.operator <<(char const *) and std::cout << str becomes std::operator<<(std::cout, s)

©Fraser Hutchinson & Cliff Green Name Lookup Rules Name resolution follows same rules as regular functions, namespace std searched for appropriate operator overload: y is resolved: –If X is class type, look for as a member of X or base of X –Look for declarations of in the context surrounding y, and –If X is defined in namespace N, look for declarations of in N –If Y is defined in namespace M, look for declarations of in M

©Fraser Hutchinson & Cliff Green Constructors and Conversions int operator +(X,Y); int operator +(Y,X); int operator +(X,Z); int operator +(Z,X); int operator +(Y,Z); int operator +(Z,X);

©Fraser Hutchinson & Cliff Green Constructors and Conversions If conversions defined: X(Y); X(Z); Would only then need to code: int operator +(X,X); The statement int val (x + y); would result in x + X(y ) invoking int operator + (X,X);

©Fraser Hutchinson & Cliff Green Prefer Prefix Increment vs Postfix Using prefix ++ typically more efficient than postfix (never less efficient) Postfix ++ requires a temporary value to be stored and returned by value Built-in types may be optimized, class types typically not (in particular, iterator classes) Good style – prefer prefix increment, only use postfix when necessary as part of expression

©Fraser Hutchinson & Cliff Green Share Implementations When Appropriate class BigInt { // … BigInt& operator+= (int); BigInt& operator++ (); // prefix increment BigInt operator++ (int); // return by value }; BigInt& BigInt::operator+= (int) { // … return *this; } BigInt& operator++ () { return *this += 1; } BigInt operator++ (int) { BigInt tmp(*this); *this += 1; return tmp; }