Ch 7. Operator Overloading Timothy Budd. Ch 7. Operator Overloading2 Introduction Almost all operators in C++ can be overloaded with new meanings. Operators.

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
COEN Expressions and Assignment
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
 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.
Data types and variables
Chapter 15: Operator Overloading
Operator Overloading in C++
1 CSC241: Object Oriented Programming Lecture No 07.
Basic Elements of C++ Chapter 2.
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Operator Overloading and Type Conversions
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
Ryan Chu. Arithmetic Expressions Arithmetic expressions consist of operators, operands, parentheses, and function calls. The purpose is to specify an.
C H A P T E R S E V E N Expressions and Assignment Statements.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Case Study - Fractions Timothy Budd Oregon State University.
Introduction to Classes in C++
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
ISBN Chapter 7 Expressions and Assignment Statements.
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:
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Learners Support Publications Constructors and Destructors.
Operator Overloading.
Chapter 18 - C++ Operator Overloading
CSE1002 – Problem Solving with Object Oriented Programming
Constructors and Destructors
Expressions and Assignment Statements
Chapter 7: Expressions and Assignment Statements
Operator Overloading; String and Array Objects
Introduction to C++ Systems Programming.
Programming with ANSI C ++
Java Primer 1: Types, Classes and Operators
Chapter 7: Expressions and Assignment Statements
Constructor & Destructor
Pointers and References
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Operator Overloading; String and Array Objects
Constructors and Destructors
Operator overloading Dr. Bhargavi Goswami
COP 3330 Object-oriented Programming in C++
Chapter 7 Expressions and Assignment Statements.
COP 3330 Object-oriented Programming in C++
Operator Overloading; String and Array Objects
Presentation transcript:

Ch 7. Operator Overloading Timothy Budd

Ch 7. Operator Overloading2 Introduction Almost all operators in C++ can be overloaded with new meanings. Operators may not look like functions but can hide function invocations. You cannot overload the meaning of operators if all arguments are primitive data types, nor can you change the precedence or associativity of operators.

Ch 7. Operator Overloading3 Figure 7.1 Overloadable Operators in C++ +-*/% ^&|~!&& ||++-- >, >= =+=-=*=/=%= &=|=^= >= []()->newdelete

Ch 7. Operator Overloading4 Overloaded Functions or Methods Operators can be defined either as functions or as member functions. How to decide which option is preferable An ordinary function is normally not permitted access to the private portions of the class, whereas a member function is allowed such access. Implicit conversions will be performed for both right and left arguments if the operator is defined in functional form, but only for the right argument if the operator is defined as a member function.

Ch 7. Operator Overloading5 Figure 7.2 Comparison Defined as an Ordinary Function class box { public: box (int v) : value(v) { } int value; }; // define meaning of comparison for boxes bool operator < (box & left, box & right) { return left.value < right.value; }

Ch 7. Operator Overloading6 Figure 7.3 Comparison Defined as a Member Function class box { public: box (int v) : value(v) { } // define meaning of comparison for boxes bool operator < (box & right) { return value < right.value; } private: int value; };

Ch 7. Operator Overloading7 Simple Binary Operators const rational operator + (const rational & left, const rational & right) { // return sum of two rational numbers rational result ( left.numerator() * right.denominator() + right.numerator() * left.denominator(), left.denominator() * right.denominator()); return result; }

Ch 7. Operator Overloading8 Simple Binary Operators Unary operations are either defined as a no- argument ordinary function or as a no-argument member function. Always return a constant value, unless you want the result to be a target for an assignment. rational a(2,3), b(7,8); (a + b) = b; // error: constant result cannot be reassigned

Ch 7. Operator Overloading9 The Comparison Operators bool operator < (const rational & left, const rational & right) { // less than comparison of two rational numbers return left.numerator() * right.denominator() < right.numerator() * left.denominator(); } // define greater than in terms of less than template bool operator > (T & left, T & right) { return right < left; }

Ch 7. Operator Overloading10 The Increment and Decrement Operators If the increment operator is overloaded, you should define both the prefix and postfix forms. Whenever you have a choice, always invoke the prefix form of the increment operator as it is usually simpler.

Ch 7. Operator Overloading11 class box { public: box (int v) : value(v) { } // prefix versions, ++aBox int operator ++ () { value++; return value; } int operator -- () { value--; return value; } int operator ++ (int) // postfix versions aBox++ { int result = value; // step 1, save old value value++; // step 2, update value return result; // step 3, return original } int operator -- (int) { int result = value; value--; return result; } private: int value; };

Ch 7. Operator Overloading12 class box { public:... const box & operator ++ () { value++; return *this; } } box mybox(3); mybox++++; // error - cannot increment constant value mybox+++= 7; // error - cannot assign to constant value mybox++ = 7; // error - cannot assign to constant value

Ch 7. Operator Overloading13 Avoid expressions whose meanings are not completely clear. int i = 5; int x = i + ++i; // ambiguous result

Ch 7. Operator Overloading14 The Shift Operators The shift operators are overloaded in exactly the same fashion as the binary arithmetic operators. cout << "m " << m << " n " << n << " average " << (n+m)/2.0 << '\n';

Ch 7. Operator Overloading15 ostream & operator << (ostream & out, const rational & value) { // print representation of rational number on an output stream out << value.numerator() << '/' << value.denominator(); return out; } Avoid the right shift of signed integer values.

Ch 7. Operator Overloading16 The Assignment Operator The assignment, comma, and address-of operators will be constructors will be constructed automatically if the programmer does not specify an alternative. class box { public: box () { value = 0; } box (int i) { value = i; } int value; }; box a(7); box b; b = a;

Ch 7. Operator Overloading17 Always redefine the assignment operator in classes that include a pointer value. const box & operator = (box & left, const box & right) { left.value = right.value; return left; } const box & operator = (box & left, int right) { left.value = right; return left; } box c; c = a; b = 2 + (a = 3);

Ch 7. Operator Overloading18 Always check for self-assignment. a = a; // make certain this works const string string::operator = (const string & right) { if (this == right) // check for self assignment return right;... }

Ch 7. Operator Overloading19 Despite the use of the assignment symbol, constructors do not use the assignment operator. box d = c; // uses copy constructor If addition and assignment are both overloaded, then += should be overloaded as well.

Ch 7. Operator Overloading20 class bigbox : public box { public: bigbox (int i, double d) : box(i), dvalue(d) { } void operator = (bigbox & right) { value = right.value; dvalue = right.dvalue; } protected: double dvalue; }; box a(3); bigbox b(3, 4.0); a = b; // legal, but sliced, box assignment, b = a; // not legal, argument must be a bigbox

Ch 7. Operator Overloading21 The Compound Assignment Operators Whenever possible, define one operator in terms of another. AnObject operator + (const AnObject & left, const AnObject & right) { AnObject clone(left); // copy the left argument clone += right; // combine with right return clone;// return updated value } const AnObject & operator += (AnObject & left, const AnObject & right) { AnObject sum = left + right; left = sum; return left; }

Ch 7. Operator Overloading22 The Subscript Operator Subscript operator is often defined for classes that represent a container abstraction. class safeArray { public: safeArray (int s) { size = s; values = new int[size]; } int & operator [ ] (unsigned int i) { assert(i < size); return values[i]; } private: unsigned int size; int * values; };

Ch 7. Operator Overloading23 The real vector data type does not check subscript ranges. safeArray v(10); v[2] = 7; v[3] = v[2] + 12; When returning a referenc, make sure that the value will continue to exist after the function exists.

Ch 7. Operator Overloading24 The Parenthesis Operator Function Object: an object that can be used as though it were a function. class LargerThan { public: // constructor LargerThan (int v) { val = v; } // the function call operator bool operator () (int test) { return test > val; } private: int val; };

Ch 7. Operator Overloading25 LargerThan tester(12); int i =... ; if (tester(i)) // true if i is larger than 12 A temporary object can be created by simply naming the class and any arguments to the constructor. list ::iterator found = find_if (aList.begin(), aList.end(), LargerThan(12));

Ch 7. Operator Overloading26 The Address-of Operator Rate to use, but when it yields a value of type void produces a class of objects that cannot have their address computed, it is useful. class box { public: box () { i = 7; } private: int i; }; box a; box * b; // b is a pointer to a box b = & a; // b now points to a

Ch 7. Operator Overloading27 The Logical Connectives Short-circuit evaluation means that in some situations only the left argument is evaluated, and the right argument is not even examined. There is no way to overload the logical operators and preserve the short-circuit evaluation.

Ch 7. Operator Overloading28 The Comma Operator The for statements in Java and C++ use the same syntax and achieve a similar result but use different mechanisms. int i, j; for (i = 0, j = 1; x[i] != 0; i++) if (x[i] == x[j]) j++;

Ch 7. Operator Overloading29 Mistakenly taping a comma instead of a period can be a very subtle programming error. x = 7,12; class box { template const T & operator, (T & right) { return right; } };

Ch 7. Operator Overloading30 An overloaded comma operator can never have the same short-circuit semantics as the original. class box { public: box (int v) : val(v) { } int value () { return val; } int operator, (box & right) { return right.value(); } private: int val; };

Ch 7. Operator Overloading31 The Arrow Operator Overloading arrow operator is useful in creating objects that have a ‘pointer-like’ behavior. The arrow operator can be defined only as a member function, and the return type must either be a pointer to a class type or an object for which the member access arrow is itself defined. A smart pointer is an object that can be used in the manner of a pointer.

Ch 7. Operator Overloading32 Example of Arrow Operator class countPointer { public: countPointer(Window * w) { count = 0; win = w; } Window * operator->() { count++; return win; } private: Window * win; int count; }; Window * x = new Window(...); // create the underlying value countPointer p(x); // create a counting pointer value p->setSize(300, 400); // invoke method in class window

Ch 7. Operator Overloading33 Conversion Operators Conversions from user types are defined by conversion operators; conversions to user types are defined by using constructors. operator double (const rational & val) { return val.numerator() / (double) val.denominator(); } rational r (2, 3); double d; d = 3.14 * double(r); // cast converts fraction to double

Ch 7. Operator Overloading34 Example of Conversion Operators class rational {... operator double () const { return numerator() / (double) denominator(); }... };

Ch 7. Operator Overloading35 Memory management Operators It is possible to overload the memory management operators new and delete, obtaining even more control over these tasks than is provided by the default implementations.

Ch 7. Operator Overloading36 Disallowing Operators An operator declared as private can be used only within a class definition. class box { public: box (int v) : val(v) { } int value () { return val; } private: void operator = (box & right) { } } box aBox (2); // create a new box box bBox (3); // and another aBox = bBox; // error -- assignment is private

Ch 7. Operator Overloading37 Implicit Functions and Invocations Implicit function definitions and implicit function invocations are invoked without the programmer directly requesting it.

Ch 7. Operator Overloading38 Implicitly Created Operations The default construct, copy constructor, destructor, assignment operator, address operator, and comma operator will all be given implicit meanings unless overridden by the programmer. class emptyBox : public box { private: box aField; };

Ch 7. Operator Overloading39 class emptyBox : public box { public: // constructors emptyBox () : box(), aField() { } emptyBox (const emptyBox & right) : box(right), aField(right.aField) { } ~emptyBox() // destructor{ // implicit deletion of aField // implicit call on parent class destructor } const emptyBox & operator = (const emptyBox & right) {// operators aField = right.aField; box::operator = (right); return *this; } emptyBox * operator & () { return * this; } template const T & operator, (const T & right) { return right; } private: box aField; };

Ch 7. Operator Overloading40 Implicit Constructors If no constructor are specified, an implicit default constructor constructor will be created. First, invoke the default constructor for the parent class if the current class was formed by using inheritance. The function will recursively apply default initialization rules for every data field. An implicit copy constructor is created if no other copy constructor is specified, even if other constructors have been defined.

Ch 7. Operator Overloading41 Implicit Destructors First, invoke destructors for every data field and then invoke the destructor for the parent class. Fields are destroyed in the opposite order listed in the class body. An implicit destructors is never considered virtual.

Ch 7. Operator Overloading42 Implicit Assignment Operator Created implicitly, takes as an argument a value of the same type as the class and recursively assigns each data field from the corresponding fields in the argument object. If there is parent class, the assignment operator for the parent class is then invoked.

Ch 7. Operator Overloading43 Implicit Address and Comma The implicit address simply returns a reference to the current object. The implicit comma operator simply returns a reference to the argument object.

Ch 7. Operator Overloading44 Implicit Function Invocations Implicit function invocation can greatly increase a program’s execution time. A copy constructor always invoked to pass a by-value object.

Ch 7. Operator Overloading45 class box { public: box () { value = 0; } box (int i) { value = i; } box (box & a) { value = a.value; } ~box() { } // destructor void operator = (box & right) { value = right.value;} operator int () { return value; } private: int value; }; box operator + (box & left, box & right) { return box(((int) left) + (int) right); }

Ch 7. Operator Overloading46 int foo (box abox) { box bbox; bbox = abox + 1; return bbox; } int main() { box mybox(3); mybox = 4; mybox = foo (mybox + 1); return 0; }

Ch 7. Operator Overloading47 box mybox(3); // integer constructor mybox = 4; // integer constructor to create temporary // assignment of temporary to variable // destructor on temporary mybox = foo (mybox + 1); // start of statement // integer constructor to create temporary // binary addition of boxes box operator + (box & left, box & right) return box(((int) left) + (int) right); // inside addition operator // conversion of left box to integer // conversion of right box to integer // integer constructor for temporary // return from addition operator mybox = foo (mybox + 1); // continuation of statement box bbox; // inside function foo // default constructor to create variable

Ch 7. Operator Overloading48 bbox = abox + 1; // start execution // integer constructor to create temporary for constant // binary addition operator for boxes box operator + (box & left, box & right) return box(((int) left) + (int) right); // inside addition operator // conversion of left box to integer // conversion of right box to integer // integer constructor for temporary bbox = abox + 1; // continue execution // assignment for boxes // destructor for temporary // conversion from box to integer // destructor for local variable bbox // return from function // destructor for temporary argument mybox = foo (mybox + 1); // continuation of statement // integer constructor converting result to box // assignment operation // destructor of temporary value // destructor of variable mybox

Ch 7. Operator Overloading49 class string { public:// constructors string (char * c)... string (const string & s)... string (int i)... }; string aString = 'a'; class string { public:// constructors string (char * c)... string (const string & s)... explicit string (int i)... };