Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.

Slides:



Advertisements
Similar presentations
Objects and Classes Part II
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1.
Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Advanced Class 6. Topics Inheritance Class methods / static methods Class data vs. instance data.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Chapter 14: Overloading and Templates
Topic 9A – Arrays as Function Arguments. CISC105 – Topic 9A Arrays as Function Arguments There are two ways to use arrays as function arguments: Use an.
Classes Separating interface from implementation
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Chapter 15: Operator Overloading
Plab – Exercise 5 C++: references, operator overloading, friends.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Module 2: User Data types #1 2000/01Scientific Computing in OOCourse code 3C59 Module 2: User defined Data Types & Operations upon them In this module.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Module 10: Simple Inheritance #1 2000/01Scientific Computing in OOCourse code 3C59 Module 10: Simple Inheritance In this module we will cover Inheritance.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Scientific Communication
XOR Operator A short digression… … to introduce another Boolean operation: exclusive- OR (XOR) ABA + B XOR.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Module 3: Steering&Arrays #1 2000/01Scientific Computing in OOCourse code 3C59 Module 3: Algorithm steering elements If, elseif, else Switch and enumerated.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Module 8: more on methods #1 2000/01Scientific Computing in OOCourse code 3C59 Module 8: More on methods: In this module we will cover: Overloading of.
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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:
1 CS161 Introduction to Computer Science Topic #9.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
1 Advanced Computer Programming Lab Calculator Project.
Chapter 8 Operator Overloading.  Operator overloading is considered one of the more useful techniques for improving readability and ease of programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Overloading operators C++ incorporates the option to use standard operators to perform operations with.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Module 7: Constructors #1 2000/2001Scientific Computing in OOCourse code 3C59 Module 7: Constructors and Destructors: In this module we will cover: Constructors.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Module 5: I/O and Strings #1 2000/01Scientific Computing in OOCourse code 3C59 Module 5: I/O and STRINGS In this module we will cover The C++ input and.
Learners Support Publications Constructors and Destructors.
1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Module 11: Polymorhism #1 2000/01Scientific Computing in OOCourse code 3C59 Module 11: Polymorphism and virtual methods In this module we will cover Polymorphism.
Module 20/21/22: The Standard Template Library
Constructors and Destructors
User-Written Functions
A Lecture for the c++ Course
This pointer, Dynamic memory allocation, Constructors and Destructor
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Constructors and Destructors
Operator overloading Dr. Bhargavi Goswami
Chapter 9 Inheritance.
Java Programming Language
Review of Previous Lesson
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading the + operator Overloading = Overloading == *, /, +=,

Module 9: Operator overloading #2 2000/01Scientific Computing in OOCourse code 3C59 Aims of this module In this module we introduce the feature of C++ which allows you to custom define the action of operators for classes. These include =, *, +, +=,....etc This feature gets used for several simplifications which you need to know about.

Module 9: Operator overloading #3 2000/01Scientific Computing in OOCourse code 3C Overloading the + operator What do you do if you want to add together two objects ???? Eg: Suppose you have written a Complex class to represent complex numbers. You would naturally wish for the following to be possible: Complex a, b, c, d ;... c = a + b ; d = a * b ; This is not automatically possible since Complex is your class and the compiler has no idea what + or * should do ???

Module 9: Operator overloading #4 2000/01Scientific Computing in OOCourse code 3C59 Another example we have already met is the ThreeVector class. Suppose we had written a cross(... ) method to take the cross product of two vectors. To use this we would have had to write: It might be much neater if we could write: ThreeVector p, q, r;... r = p.cross( q ) ; ThreeVector p, q, r;... r = p * q ; but again, this is obviously not automatically possible since * is not defined for ThreeVectors

Module 9: Operator overloading #5 2000/01Scientific Computing in OOCourse code 3C59 Such operations are only possible if you can tell the compiler which procedure to invoke in each case. This is the feature provided by: Operator Overloading This feature allows you to custom define the meaning of operators like : =, +, -, *, /, +=, >>,..... when applied to objects of a class. [See text books for full list]

Module 9: Operator overloading #6 2000/01Scientific Computing in OOCourse code 3C59 The feature is based upon the fact that an operator like: + is formally equivalent to a method called: operator+ In other words the following two bits of code are identical in function: c = a + b ; c = a.operator+( b ) ; therefore to define + we provide an overloaded method: operator+(... ) in the normal way

Module 9: Operator overloading #7 2000/01Scientific Computing in OOCourse code 3C59 As example we will write the Complex class and provide the + operator. Here is the class declaration: class Complex { public: //Constructor Complex( float re, float im ) ; //+ Operator Complex operator+( Complex& k ) ; private: float real ; float imag ; };

Module 9: Operator overloading #8 2000/01Scientific Computing in OOCourse code 3C59 class Complex { public: //Constructor Complex( float re, float im ) ; //Operators Complex operator+( Complex& k ) ; private: float real ; float imag ; }; Constructor with obvious arguments

Module 9: Operator overloading #9 2000/01Scientific Computing in OOCourse code 3C59 class Complex { public: //Constructor Complex( float real, float imag ) ; //Operators Complex operator+( Complex& rhs ) ; private: float real ; float imag ; }; Declare we are going to overload two operators, + and *. Both are binary operators therefore need an argument It has to return a Complex as a result of the addition, I.e. we will want to write c = a + b; Where a,b,c are Complex types

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex Complex::operator+( Complex& rhs ) {...now lets write the operator+ method.... Returns a Complex number Method name Takes a Complex reference as argument

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex Complex::operator+( Complex& rhs ) { Complex result ; Create a complex number to put the result into

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex Complex::operator+( Complex& rhs ) { Complex result ; result.real = real + rhs.real ; result.imag = imag + rhs.imag ; Do the maths !

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex Complex::operator+( Complex& rhs ) { Complex result ; result.real = real + rhs.real ; result.imag = imag + rhs.imag ; return result ; } Return the final result

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Why did we make this method return a Complex number ? You might think its obvious (good if so !!) i.e a + b must produce a result, and what else can you do with it but return it ? In case you dont think its obvious, lets look at what in effect actually happens For the purposes of this explanation suppose we have created three complex numbers... Complex a, b, c ;....

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Later in the program there is a line like this: It should be clear from this that the method called operator+ needs to return a Complex object to be placed into the variable called c. c = a.operator+ ( b ) ; c = a + b ; Now imagine the + operation replaced by the method equivalent:

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Student exercise Write a Complex class as already indicated (I.e. with a constructor and a + method) Add the - * operators Write a program to demonstrate their use Complex/ Complex.h Complex.cpp Comtest.cpp

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C Operator = We glossed over the = operation earlier i.e: when we wrote (the equivalent of) : Complex a, c ;... c = a ; I "implicitly" asserted that setting object1 = object2 required no thought, i.e. that it was automatic.

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex a, c ;... c = a ; In fact for "simple" objects the compiler does provide a quite sensible default action for = It simply does a "memberwise" copy I.e. each member variable in a is copied into the corresponding member variable in c In most cases this is fine.... but not always.…beware of pointers…. So in general you should provide your own = operator

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 class Complex { public: //Constructor Complex( float re, float im ) ; //Operators Complex operator+( Complex& rhs ) ; void operator=( Complex& rhs ) ; private: float real ; float imag ; }; First declare the overloading Here is how you might overload the = operator Note: in practice it is not quite done like this - we come to the difference in a few slides

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 void Complex::operator=( Complex& rhs ) { real = rhs.real ; imag = rhs.imag ; return ; }....and here is the corresponding code... The members of the object for which the method is called (i.e. the LHS) get set to the members of the argument (the RHS). Recall the equivalence: c = a ; c.operator=( a ) ;

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex a,b,c ;... c = b = a ; Why did we say that it is not quite done this way ? It is connected with "chaining" of operations. We require the following to work: c = ( b = a ) ; If you interpret this as: then it is clear that the b = a operation had better return a complex number in order for it to appear as the RHS of c = (some complex number) ; If still in any doubt then consider the equivalence: c = b.operator=( a )

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 class Complex { public: //Constructor Complex( float re, float im ) ; //Operators Complex operator+( Complex& rhs ) ; Complex operator=( Complex& rhs ) ; private: float real ; float imag ; };...therefore here is a better overloaded = operator

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex Complex::operator=( Complex& rhs ) { //Do the maths on the object which = is called for real = rhs.real ; imag = rhs.imag ; //Make a copy to return Complex result( real, imag ) ; return result; }....and here is the corresponding code...

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex Complex::operator=( Complex& rhs ) { //Do the maths on the object which = is called for real = rhs.real ; imag = rhs.imag ; return *this; } For the advanced: In fact for an object to make a copy of itself for this purpose is a waste of space and time It is not necessary, instead it can simply use this You might need to think about this if it is the first time you have used this return *this causes the object itself to be copied as the return value.

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex& Complex::operator=( Complex& rhs ) { //Do the maths on the object which = is called for real = rhs.real ; imag = rhs.imag ; return *this; } For the advanced: you can also avoid the copy on return by returning a reference to your self instead of a copy of yourself. You can do this because (i) you(the object) contain the required return value (i) you are stable and will not vanish upon return If you do not understand this now - do not worry

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C Boolean operator == You would want to overload the boolean == operator so that you can do tests like: Complex a, c ;... if( c == a ) {... }  Whole Class excercise on whiteboard 

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex& Complex::operator=( Complex& rhs ) { //Do the maths real = rhs.real ; imag = rhs.imag ; //Make a copy to return Complex result( real, imag ) ; return result; } Discussion 1: why wouldn’t this have worked ? ? 15.6 Discussion on returning of references

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Complex& Complex::operator+( Complex& rhs ) { ??? some code to do the maths ??? return ???something??? ; } Related discussion 2: why can you only return a reference for some operators =, += and not others +, -, * I.e why can you not find some code to implement this.. ?

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 The answer to both questions is essentially the same: Provided the result of the operation is held in the one of the operand objects (i.e. c = a places the result in c ) then the resulting object can always pass a reference to itself as it by defn exists outside the scope of the method. If however the result of the operation is not actually held in one of the operands, i.e. a + b does not put the result in either a or b, then you have to make a new object for the result and pass that object as a return argument not a reference as the new object will go out of scope upon returning.

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Student exercise Add the following operators to your Complex class / (if you can remember how to divide complex numbers) = += Complex/ complex.h complex.cpp

Module 9: Operator overloading # /01Scientific Computing in OOCourse code 3C59 Summary of Module 9: Operator Overloading In this module we have covered the following topics. Overloading + equivalence of "+" with "operator+" declaring and writing the operator+ method return values from operator+ Overloading of = return value from operator= use of *this Overloading of == Some others needed for the Complex class