Chapter 14 Operator Overloading: What does + mean? Consider the code below. Note the multiple uses of “+”. #include using namespace std; int main() { int.

Slides:



Advertisements
Similar presentations
Chapter 12 Lists and Iterators. List Its an abstract concept not a vector, array, or linked structure. Those are implementations of a List. A list is a.
Advertisements

Operator Overloading Fundamentals
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Operator Overloading in C++
1 CSC241: Object Oriented Programming Lecture No 07.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Pointer Data Type and Pointer Variables
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Chapter 6 Vectors and arrays: Arrays: Run the following code. Anything unusual? #include using namespace std; #define N 10 #define M 11 int main() { int.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
Operator Overloads Part2. Issue Provide member +(int) operator Rational + int OK int + Rational Error.
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 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 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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:
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.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Recap: Interfaces A class is a logical abstraction, but an object has physical existence. access-specifier can be: public: Allow functions or data to be.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Overloading operators C++ incorporates the option to use standard operators to perform operations with.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
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.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
1 Introduction to Object Oriented Programming Chapter 10.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Chapter 2 Objects and Classes
Types CSCE 314 Spring 2016.
7. Inheritance and Polymorphism
Motivation and Overview
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Jim Fawcett Copyright ©
The dirty secrets of objects
Chapter 2 Objects and Classes
group work #hifiTeam
Operator Overloading; String and Array Objects
Overloading functions
Java Programming Language
Jim Fawcett Copyright ©
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Chapter 14 Operator Overloading: What does + mean? Consider the code below. Note the multiple uses of “+”. #include using namespace std; int main() { int a,b=5,c=8; string x, y = “Five”, z = “Six”; a = b + c; x = y + z; cout << a << “ “ << x << endl; }

The operator “+” is an overloaded operator. That is, it has different meanings depending on how it is used (its context). Programmers can give new meaning to existing operators. This is operator overloading.

Example: if x and y are objects, what does x+y mean? What if x and y are fractions? x = a/b and y = c/d; Then x + y= (ad+bc)/bd?

P. 547 shows overloadable operators. Fraction case study Section Also on program demo. Step through various constructors Discuss the normalize method

Overloaded Operators: implement as member functions or non-member functions (aka helper functions). Note that there are some of each in demo07. Which is best?

Fraction class: code shows ‘+’ operator as both member and helper, though if one is used the other commented out. If a member function then x+y is the same as x.operator+(y)

Thus, x+2 is OK because 2 is automatically promoted to a fraction using the default constructor but 2+x is not OK since it is interpreted as 2.operator+(x) Similar to example on p If a helper function, either is OK. See code.

Similar comments for other arithmetic operators ‘-’, ‘*’, and ‘/’. Note the productivity hint on page 559. Note the productivity hint on page 560.

Note the advanced topic on page 561. This is important because it’s a basic design issue – when to use member functions or helper functions. Same issue as with ‘+’ … symmetry is important with the ‘==‘ (and other comparison) operators

Overloading the ++ operators – page 564. Note that one returns a reference and the other returns a copy. Note the prose on page 565 Note the quality tip on page 565. Skip the section on overloaded operators and iterators. It requires things we’ve not covered yet.

Overloading the assignment operator p Not done for the Fraction class; C++ provides its own overaloded operator – THOUGH THIS CAN GET YOU IN TROUBLE!!! (more later in the semester). See the productivity hint on page 568.

Overloading conversion operators. Remove comments around the double operator. Note the error. What is it telling you?

Adds ambiguity to the code. C++ does not know what to do. For example, the overloaded operator a = a+2 does not work if the conversion operator double() is included in the class definition. Compiler error that detects there is an ambiguity between the two.

Reason: Compiler sees “b=a+2” and must interpret “+”. It knows that 2 can be converted to a fraction and could use the + that adds two fractions. It also knows that “a” can be converted to a double and can use the + that adds a double and an int.

Thus the message “error C2666: ‘operator`+’’ : 2 overloads have similar conversions”. More at [ spx?scid=kb;en-us;106392]. spx?scid=kb;en-us;106392

Removing the double() conversion operator will fix this. Can also fix by adding additional overloaded operators. For example: Fraction operator+(int left, const Fraction& right) { Fraction temp(left); return temp + right; }

This would allow an expression of the form a = 2 + a. However, would need yet another overloaded operator to allow a + 2. Note the tips, errors, and advanced topics on pages Putting explicit before the constructor Fraction (int t) prevents the automatic conversion from an int to a Fraction in a+2.

Overloading the subscript operator: See the SafeArray class on p. 573 AND the code snippet from the notes. The [] operator hides the details of how an element is accessed. This is WHY we do encapsulation.

Note that the overloaded operator is written as a member function. Note the error if I try to write x[2] = 99 in the main code. Must write another overloaded operator[] (non-constant) that returns int& (i.e. an lvalue). Functions that overload operators should return reference types if the operator will be used as an lvalue.

See example on p. 574 on overloading the function call operator. Again, must be written as a member function.

Program demo08 has overloaded operators >. At this point it’s mostly just a matter of replacing read() and write() methods with >> and > operator to work with ANY array. In the overloaded operator code you’ll apply > to each array element which could be any type or class. This allows a single method to be used with a large range of types. Very generic.

Demo08 does show how this can be done. Put a break point in the Manager destructor and show how writing BOTH the account and customer lists is done via the SAME overloaded << operator.