Operator Overloading Programming in C++ Fall 2008 Dr. David A. Gaitros

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Abstract Data Type Fraction Example
Operator Overloading Back to Fractions.... Implementing an Object We’ve talked at length about object- orientation. – We’ve looked heavily at encapsulation.
Class and Objects.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Abstract Data Types Development and Implementation.
CS-240 Operator Overloading Dick Steflik. Operator Overloading What is it? –assigning a new meaning to a specific operator when used in the context of.
1 Lab Session-XII CSIT121 Fall 2000 b Namespaces b Will This Program Compile ? b Master of Deceit b Lab Exercise 12-A b First Taste of Classes b Lab Exercise.
Abstract Data Type. COMP104 Slide 2 Summary l A class can be used not only to combine data but also to combine data and functions into a single (compound)
CMSC 2021 Stream I/O Operators and Friend Functions.
Programmer-defined classes Part 3. A class for representing Fractions public class Fraction { private int numerator; private int denominator; public Fraction(int.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading in C++
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
CSIS 123A Lecture 5 Friend Functions Glenn Stevenson CSIS 113A MSJC.
Overloading Operators. Operators  Operators are functions, but with a different kind of name – a symbol.  Functions.
Separate Compilation. A key concept in programming  Two kinds of languages, compilation (C, Pascal, …) and interpretation (Lisp, …, Matlab, Phython,
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
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 #5 Introduction to C++
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Inheritance One of the most powerful features of C++
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
Operator Overloading. Objectives At the conclusion of this lesson, students should be able to Explain what operator overloading is Write code that overloads.
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.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Operator Overloading Week 5.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
Overview Class Scope Review: Object parameters passed by value reference constant reference Friend function Overloading operator.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Operator Overloading Chapter Objectives You will be able to Add overloaded operators, such as +,-, *, and / to your classes. Understand and use.
Friend Functions. Problem u Assuming two Complex objects u How would one add two numbers? W + X Complex operator+(const Complex& w, const Complex& x);
Object Oriented Programming COP3330 / CGS5409.  Arithmetic Operator Overloading  Increment (++) / Decrement (--)  In-class exercise.
Operator Overloading.
Andy Wang Object Oriented Programming in C++ COP 3330
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value A copy of the argument’s value.
Regarding assignment 1 Style standards Program organization
C++ First Steps.
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
C++ Templates.
Andy Wang Object Oriented Programming in C++ COP 3330
Object Oriented Programming COP3330 / CGS5409
Object-Oriented Design (OOD) and C++
A First C++ Class – a Circle
Andy Wang Object Oriented Programming in C++ COP 3330
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
More on Classes Programming in C++ Fall 2008
Andy Wang Object Oriented Programming in C++ COP 3330
Fraction Abstract Data Type
Operator Overloading; String and Array Objects
Operator Overloading.
C++ Compilation Model C++ is a compiled language
COP 3330 Object-oriented Programming in C++
Development and Implementation
Class rational part2.
Presentation transcript:

Operator Overloading Programming in C++ Fall 2008 Dr. David A. Gaitros

Operator Overloading In working with machine code and assembly language programs, there are different operations that perform the same basic function for different types of data. For instance, the machine instruction to add two binary numbers together differs from that operation that is meant to add two packed decimal numbers. In Higher level languages when adding numbers, we want to abstract the notion of basic arithmetic and not worry about using the correct machine function. Thus, the concept of operation overloading. There are built-in operations already such as +, -, *, /, =, ==, %, etc.

Operator Overloading We can already overload functions. – Overloaded functions have the same name but different signatures ( different parameters and return values). Operator Overload in C++ – In reality it is just a function call using special notation. – C++ already does some operator overloading. Example: The “+” operator works with floats, nits, doubles, and chars. – Operator overloading is done for the purpose of making the use of familiar notation in your program. For instance, let us say you wanted to add two matrices. You could overload the “+” operator to accomplish this.

Operator Overloading Rules for Operator Overloading – Overloading an operator cannot change it’s precedence. – Overloading an operator cannot change it’s associativity. – Overloading an operator cannot change the number of operands. – It is not possible to create new ones, only new versions of existing ones. – Operator meaning on built-in features cannot be changes. For instance you cannot change the “+” for integers.

Operator Overloading Format – The name of an operator is always a conjunction of the keyword operator and than the symbol itself. – Example: operator+ Operator++ Operator- - Operator – Operator << Operator == Operator = – NOTE: Overloaded operators are not member functions.

Operator Overloading Operators that can be overloaded: +-*/%^ &|~!=< >+=-=*=/=%= ^=&=|=<<>>>>= <<===!=<=>=&& ||++--->*,-> []()newdeletenew[]delete[]

Operator Overloading as a Friend Function friend Fraction Add (Fraction f1, Fraction f2); // Sample Call Fraction n1, n2, n3; n3= Add(n1,n2);

The “Fraction” Class Makefile driver: driver.o fraction.o g++ -o driver driver.o fraction.o driver.o: driver.cpp g++ -c driver.cpp fraction.o: fraction.h fraction.cpp g++ -c fraction.cpp

The “Fraction Class” Header File #ifndef FRACTION_H #define FRACTION_H // ************************************** // * is needed here so the compiler * // * is aware of the overload of ostream and * // * istream. * // ************************************** #include using namespace std; class Fraction { friend ostream& operator<<(ostream &S, const Fraction &f2); friend istream& operator>>(istream &S, Fraction &f2);

The “Fraction Class” public: Fraction(); Fraction(int, int); bool setdenominator(int ); bool setnumerator(int); int getdenominator(); int getnumerator(); Fraction Add(Fraction &f1); private: int denominator; int numerator; }; #endif

The “Fraction Class” Implementation File (.cpp) #include #include "fraction.h" using namespace std; ostream & operator<<(ostream &S,Fraction &f2) { S << f2.getnumerator() << '/' <<f2.getdenominator() ; return S; } istream & operator>>(istream &S, Fraction &f2) { int n,d; char c; S >> n>>c>>d; f2.setnumerator(n); f2.setdenominator(d); }

The “Fraction Class” The constructors in the.cpp file Fraction::Fraction() { numerator=1; denominator=1; } Fraction::Fraction(int n, int d) { this->setnumerator(n); this->setdenominator(d); }

The “Fraction Class” Set functions in the.cpp file bool Fraction::setdenominator(int d) { if(d !=0) { denominator = d; return true; } else denominator=1; return false; } bool Fraction::setnumerator(int n) { numerator = n; return true; }

The “Fraction Class” get functions in the.cpp file bool Fraction::setnumerator(int n) { numerator = n; return true; } int Fraction::getdenominator() { return denominator; } int Fraction::getnumerator() { return numerator; }

The “Fraction Class” The Add Function in the.cpp file Fraction Fraction::Add(Fraction &f1) { Fraction R1=f1; Fraction R2; R2.numerator =this->numerator; R2.denominator = this->denominator; R1.numerator = R1.numerator * R2.denominator; R2.numerator = R2.numerator * R1.denominator; R1.denominator = R1.denominator * R2.denominator; R2.denominator = R1.denominator; R1.numerator = R1.numerator + R2.numerator; return R1; }

Overload of the “+” operator for the Fraction class as a “Friend” // ******************************** // * This goes in the.h file * // ******************************** friend Fraction &operator+( Fraction f1, Fraction f2);

Overload of the “+” operator for the Fraction class as a “Friend” // ********************************** // * This goes in the.cpp file * // ********************************** Fraction &operator+(Fraction f1, Fraction f2) { Fraction R1=f1; Fraction R2=f2; R1.numerator = R1.numerator * R2.denominator; R2.numerator = R2.numerator * R1.denominator; R1.denominator = R1.denominator * R2.denominator; R2.denominator = R1.denominator; R1.numerator = R1.numerator + R2.numerator; return R1;}

Overload of the “+” operator for the Fraction class as a “Friend” // * ******************************* // * What the calls look like in * // * the driver or main routine. * // ********************************* Fraction F1,F2,F3,F4; cin >> F1; cin >> F2; cin >> F3; cin >> F4; F1 = operator+(F1,F2); F1= F1 + F2; F1= F1 + F2 + F3 + F4;

Operator Overloading as a member function // ******************************** // * This goes in the.h file * // * Note, there is only one * // * parameter. * // ******************************** Fraction operator+( Fraction f1);

Operator Overloading as a member function // * **************************************** // * Note: Only passing in one parameter. * // ****************************************** Fraction Fraction::operator+(Fraction &F1) { Fraction R1=f1; Fraction R2; R2.numerator =this->numerator; R2.denominator = this->denominator; R1.numerator = R1.numerator * R2.denominator; R2.numerator = R2.numerator * R1.denominator; R1.denominator = R1.denominator * R2.denominator; R2.denominator = R1.denominator; R1.numerator = R1.numerator + R2.numerator; return R1; }

Operator Overloading as a member function // * ******************************* // * What the calls look like in * // * the driver or main routine. * // ********************************* Fraction F1,F2,F3,F4; cin >> F1; cin >> F2; cin >> F3; cin >> F4; F1 = F1.operator+(F2); F1= F1 + F2; F1= F1 + F2 + F3 + F4;

Some other possible arithmetic operators Prototypes only // multiplication overload for Fractions friend Fraction operator*(Fraction f1, Fraction f2); // addition operator to add a Fraction and an integer friend Fraction operator+(Fraction f, int n); // same as above, but this one allows the int to come first in the call friend Fraction operator+(int n, Fraction f); Note: The last two are not really needed but will they both work for both the Friend and Member function. Remember that in the case of the member function, the first operator Is the calling function and must be a member of the class.

Overloading of comparison operators Very handy to do this. Many times we want to compare two objects just as we would an integer, real, or character. Allows us to maintain the consistency of the code. // As a friend function friend bool Equals(Fraction f1, Fraction f2); // Sample call if(Equals(n1,n2)) cout << “n1 is equal to n2”)<< endl; // As an operator overload friend bool operator==( Fraction f1, const Fraction f2); // Sample Call if (n1 == n2 ) cout << “n1 is equal to n2”)<< endl;

Overloading the > extraction operators > work with basic types already defined by the C++ language and included in iostream. They ( >) do not work with user defined types and classes. Your own classes or types must be converted into one of the basic types in order for these to work. This is done through overloading.

Overloading the > extraction operators The > are binary operators. – The first parameter MUST be an ostream object. – The > are almost always defined as friends (outside functions or members). – The second parameter is whatever type you define. – Your new defined function must convert the new type into a basic type expected by iostream.

Overloading the > extraction operators // ************************************ // * Another version with a leading * // * whole number plus the fraction. * // ************************************ istream & operator >> (istream& inputStream, Fraction & f1) { integer i1, i2, i3; char slash; cin >> i1; cin >> i2; cin >> slash; cin >> i3; // add error checking here }