Operator Overloading. C++ 2 Outline  General technique  Overloading of the assignment operator  Overloading the increment and decrement operators.

Slides:



Advertisements
Similar presentations
Complete Structure class Date {class Date { private :private : // private data and functions// private data and functions public :public : // public data.
Advertisements

4 Control Statements: Part 1.
Chapter 2: Basic Elements of C++
Lecture 14 Today: Overloading: Revision on this Revision on increment operators the assignment operator the [] operator Book: p , 215,
Programming In C++ Spring Semester 2013 Lecture 3 Programming In C++, Lecture 3 By Umer Rana.
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
The "if structure" is used to execute statement(s) only if the given condition is satisfied.
Write a function to calculate the cubic function: y = 4x 3 + 2x 2 –5x – 4 The function should return y for any given value of x. Question One #include.
Review of Inheritance. 2 Several Levels of Inheritance Base Class B Derived class D Derived class D1.
CSC 221: Computer Programming I Fall 2001  conditional repetition  repetition for: simulations, input verification, input sequences, …  while loops.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 102 Computer Programming II (Lab:
8.5 Factoring x 2 + bx + c. Factoring with Positives x 2 + 3x + 2 ◦Find two factors of 2 whose sum is 3. ◦Helps to make a list (x + 1)(x + 2) Factors.
Chapter 8. Operator Overloading Operator overloading gives the opportunity to redefine C++ Operator overloading refers to redefine C++ operators such.
Operator Overloading Fundamentals
Chapter 04 (Part III) Control Statements: Part I.
Basic Control Structures Control order of execution of statements sequential selection iteration - Repeat some action while a certain condition is true.
Chapter 2- Visual Basic Schneider
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 9/28/07CS150 Introduction to Computer Science 1 Loops section 5.2, 5.4, 5.7.
CS150 Introduction to Computer Science 1
Compound Operators 03/07/11. More Operators, First Section 4.4.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Chapter 6 - Visual Basic Schneider
1 Fall 2008ACS-1903 Ch 4 Loops and Files while loop do-while loop Other topics later on …
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
For Loops Programming. COMP102 Prog Fundamentals I: for Loops/Slide 2 The for Statement condition action true false initialization update.
Lecture 17: 10/29/2002CS149D Fall CS149D Elements of Computer Science Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
For Repetition Structures (L13) * General Form of the for Statement * Components of a Typical for Header * Pre/Postincrement of the Counter * Stream Manipulator.
Lecture 4 Introduction to Programming. if ( grade ==‘A’ ) cout
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Completing the Basic (L06)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Java course. Assignment #2, due: Feb. 27, (20) (a) Tell the difference between the abstract class and the interface. (b) Tell the difference between.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Hierarchy of C++ data types. Hierarchy of C++ data types Contd.. Note : The modifies signed, unsigned, long and short may be applied to character and.
Exception Handling. C++ 2 Outline  Throwing and handling exceptions  Exceptions of different types  The new operator and the exceptions  Re-throwing.
CPTG286K Programming - Perl Chapter 4: Control Structures.
Objective: Students will be able to: Declare and use variables Input integers.
Homework #5: Pointers, Dynamic Arrays and Inheritance By J. H. Wang Jun. 5, 2009.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
While Loops 10/14/13. Repetition Allows a program to do tasks over and over. Very powerful because the computer is fast and accurate.
1 COMS 261 Computer Science I Title: Classes Date: November 9, 2005 Lecture Number: 29.
Sum of Arithmetic Sequences. Definitions Sequence Series.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
Lecture 5: Layers of Control. Nested while Loops Problem Multiplying two numbers and outputting the result only if they are both less than 5. (i.e. Start.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
arithmetic operator & cin I.Mona Alshehri The output formatting functions setw(width) setw(n) - output the value of the next expression in n columns.
 2006 Pearson Education, Inc. All rights reserved if…else Double-Selection Statement if – Performs action if condition true if…else – Performs.
JavaScript: Control Structures I Outline 1 Introduction 2 Algorithms 3 Pseudocode 4 Control Structures 5 if Selection Structure 6 if/else Selection Structure.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
Section 3 Review Mr. Crone.
for Repetition Structures
ASSIGNMENT NO.-2.
OPERATORS (2) CSC 111.
Increment and Decrement
More C expressions ANSI-C.
Introduction to Programming
Introduction to Programming
Structured Program Development in C
Unary Operators ++ and --
Lecture Notes – Week 3 Lecture-2
Lec 6.
Repetition Control Structure
Operator Overloading.
CS149D Elements of Computer Science
Programming Fundamental
Presentation transcript:

Operator Overloading

C++ 2 Outline  General technique  Overloading of the assignment operator  Overloading the increment and decrement operators

C++ 3 General Technique  In the case of our MyVector class, if v1 and v2 are two vectors, then the sum of them can be printed out with the following statement: v1.Sum(v2).Display();  But we would like to do this, by using the form: cout << v1 + v2;  Thus, we have to overload the << and + operators.

C++ 4 General Rules  There is no way to define new operators, just the existing ones can be overloaded.  There are some operators which cannot be overloaded, like the scope operator (::), and the member selection operator (.).  There is no possibility to change the nature of an operator (binary or unary, and associativity).

C++ 5 How to Overload an Operator?  Define a special member function (or friend function).  The name of the function is composed of the operator keyword, and the respective operator.

C++ 6 The Class Declaration class MyVector { private: int *elem; int dim; public: MyVector(int *e, int d); MyVector(const MyVector & v); ~MyVector(); void SquareVect(); MyVector operator +(MyVector & v); ostream& Display(ostream & s) const; };

C++ 7 The + Operator MyVector MyVector::operator +(MyVector & v) { if (dim != v.dim) throw "Different size"; int* x = new int[dim];

C++ 8 The + Operator for(int i = 0; i < dim; i++) x[i] = elem[i] + v.elem[i]; MyVector t(x, dim); delete [] x; return t; }

C++ 9 The Display Member Function ostream & MyVector::Display(ostream & s) const { for(int i = 0; i < dim; i++) s << elem[i] << '\t'; return s << endl; }

C++ 10 The Inserter Operator ostream& operator << (ostream & s, const MyVector & v) { return v.Display(s); }

C++ 11 The main Function int main() { int x[]={1, 2, 3, 4, 5}; MyVector v1(x, 5); int y[]={2, 4, 6, 8, 10}; MyVector v2(y, 5); cout << v1+v2; }

C++ 12 Overloading of the Assignment Operator  By default a member-wise assignment is defined.  Generally this gives good results if there are no pointer data members.  In other case we should overload the assignment operator.

C++ 13 Example 1 (No Assignment Operator Needed) #include using namespace std; class Fraction { int numerator; int denominator; public: Fraction(int a = 0, int b = 1); Fraction operator *(Fraction& r); ostream& Display(ostream &s); };

C++ 14 Constructor Fraction::Fraction(int a, int b) { numerator = a; denominator = b; }

C++ 15 The * operator Fraction Fraction::operator *(Fraction& r) { return Fraction(numerator * r.numerator, denominator * r.denominator); }

C++ 16 The Display Member Function ostream& Fraction::Display(ostream &s) { return s << numerator << " / " << denominator; }

C++ 17 The << operator ostream& operator <<(ostream& s, Fraction & t) { return t.Display(s); }

C++ 18 The main Function int main() { Fraction x(3, 5); Fraction y(2, 7); Fraction z; z = x * y;// OK. No error cout << z;// Result: 6 / 36 }

C++ 19 Example 2  MyVector has a data member (elem), which is a pointer, thus we must overload the assignment operator.  In other case, the assignment v2 = v1;  leads to a running-time error.

C++ 20 The Error in Visual C++

C++ 21 The MyVector Class class MyVector { private: int *elem; int dim; public: MyVector(int *e, int d); MyVector(const MyVector & v); ~MyVector(); void SquareVect(); MyVector operator +(MyVector & v); MyVector& operator =(const MyVector& v); ostream& Display(ostream & s) const; };

C++ 22 The Assignment Operator MyVector& MyVector::operator =(const MyVector& v) { if (this != &v) { delete[] elem; dim = v.dim; elem = new int[dim]; for(int i = 0; i < dim; i++) elem[i] = v.elem[i]; } return *this; }

C++ 23 The main Function int main() { int x[]={1, 2, 3, 4, 5}; MyVector v1(x, 5); int y[]={2, 4, 6, 8, 10}; MyVector v2(y, 5); cout << v1+v2; v2 = v1; cout << v2; }

C++ 24 Output

C++ 25 Other Assignment Operators  All op= operators can be overloaded, where op is a binary arithmetical or bitwise operator.  By default these operators are not overloaded.  If op is already overloaded, then we can use it, and the current object can be accessed in the form: *this.

C++ 26 The MyVector Class class MyVector { private: int *elem; int dim; public: MyVector(int *e, int d); MyVector(const MyVector & v);

C++ 27 The MyVector Class ~MyVector(); void SquareVect(); MyVector operator +(const MyVector & v); MyVector& operator =(const MyVector& v); MyVector& operator +=(const MyVector& v); ostream& Display(ostream & s) const; };

C++ 28 The += operator MyVector& MyVector::operator +=(const MyVector& v) { return *this = *this + v; }  Because the formal parameter v is declared as const we must have the same in case of the + operator.

C++ 29 If there is no const  If this is not the case, then we can define the += operator in the following form: MyVector& MyVector::operator +=(const MyVector& v) { return *this = *this + const_cast (v); }

C++ 30 The main Function int main() { int x[]={1, 2, 3, 4, 5}; MyVector v1(x, 5); int y[]={2, 4, 6, 8, 10}; MyVector v2(y, 5); v2 += v1; cout << v2; }

C++ 31 The Copy Constructor and the Assignment Operator MyVector v2(v1);// copy constructor MyVector v2 = v1;// copy constructor MyVector v2; // default constructor v2 = v1; // assignment operator

C++ 32 Overloading the Increment and Decrement Operators  pre increment  post increment  pre decrement  post decrement

C++ 33 Example #include using namespace std; class Fraction { int numerator; int denominator; public:

C++ 34 Example Fraction(int a = 0, int b = 1); Fraction operator *(Fraction& r); Fraction& operator ++(); // pre increment Fraction operator ++( int ); // post increment ostream& Display(ostream &s); };

C++ 35 Constructor Fraction::Fraction(int a, int b) { numerator = a; denominator = b; }

C++ 36 Pre Increment Operator Fraction& Fraction::operator ++() { numerator += denominator; return *this; }

C++ 37 Post Increment Operator Fraction Fraction::operator ++( int ) { Fraction t(numerator, denominator); numerator += denominator; return t; }

C++ 38 The main Function int main() { Fraction x(3, 4); Fraction y(3, 4); Fraction z; z = x++; cout << "z = " << z << endl; cout << "x = " << x << endl; z = ++y; cout << "z = " << z << endl; cout << "y = " << y << endl; }

C++ 39 Output z = 3 / 4 x = 7 / 4 z = 7 / 4 y = 7 / 4