Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.

Slides:



Advertisements
Similar presentations
Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
Advertisements

Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3.
Operator Overloading Fundamentals
Class and Objects.
Operator Overloading. Basics Define operations on user-defined data types –Perform same operation as it is supposed to but, with operands of the user-defined.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Chapter 15: Operator Overloading
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator overloading Object Oriented Programming.
Operator Overloading in C++
1 CSC241: Object Oriented Programming Lecture No 07.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Review of C++ Programming Part II Sheng-Fang Huang.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
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
Chapter 12: Adding Functionality to Your Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Function and Operator Overloading. Overloading Review of function overloading –It is giving several definitions to a single function name –The compiler.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Operator overloading and type convesions BCAS,Bapatla B.mohini devi.
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.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
Unit: 7 Operator Overloading and Type Conversions Course: MBATech Trimester: II.
Operator Overloading Operator Overloading allows a programmer to define new types from the built-in types. –Operator Overloading is useful for redefining.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
CS Object Oriented Programming Using C++
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Unit VI polymorphism. Md.Jaffar Sadiqsumalatha Polymorphism refers to : one name, many forms. Polymorphism is of two types:  Compile time polymorphism.
CS212: Object Oriented Analysis and Design Lecture 11: Operator Overloading-I.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
1 CSC241: Object Oriented Programming Lecture No 08.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
CS212: Object Oriented Analysis and Design Polymorphism (Using C++)
Operator Overloading.
Chapter 18 - C++ Operator Overloading
CSE1002 – Problem Solving with Object Oriented Programming
Overloading C++ supports the concept of overloading Two main types
Operator Overloading Ritika Sharma.
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
Overloading Operator MySting Example
Visit for more Learning Resources
Object-Oriented Design (OOD) and C++
Polymorphism in C++ Operator Overloading
Operator Overloading BCA Sem III K.I.R.A.S.
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
COP 3330 Object-oriented Programming in C++
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Chapter 18 - Operator Overloading
Presentation transcript:

Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion and Stream-Extraction Operators. Overloading Unary Operators. Overloading Binary Operators.

Operating overloading C++ enables the programmer to overload most operators to be sensitive to the context in which they are used. The compiler generates an appropriate function or method call based on the operator's use. To overload an operator, write a function definition; the function name must be the keyword operator followed by the symbol for the operator being overloaded. To use an operator on class objects, that operator must be overloaded - with two exceptions. The assignment operator (=) may be used with two objects of the same class to perform a default memberwise assignment without overloading. The address operator (&) also can be used with objects of any class without overloading; it returns the address of the object in memory. The point of operator overloading is to provide the same concise expressive power for user-defined data types that C++ provides with its rich collection of operators that work on built-in types. Operator overloading is not automatic - the programmer must write operator overloading functions to perform the desired operations. Sometimes these functions are best made methods; sometimes they are best as friend functions.

Restrictions on Operator Overloading +-*/%^&| ~!=<>+=-=*= /=%=^=&=|=<<>>>>= <<===!=<=>=&&||++ --->*,->[]()newdelete new[]delete[]

Fundamentals of Operator Overloading Process that enables C++’s operators to work with class objects. C++ has ability to provide the operators with a special meaning for a data. The mechanism of giving such special meanings to an operator is known as operator overloading. C++ can overload the entire C++ operator except following: 1. Class member access operator (. ) 2. Scope resolution operator (::) 3. Size operator (sizeof) 4. Conditional operator (? :) Why do we need operator overloading? Do we really need it? For instance, compare the following syntaxes to perform addition of two objects a and b of a user-defined class Fraction (assume class Fraction has a member function called add() which adds two Fraction objects): c = a.add (b); c = a+b; After overloading the appropriate operators, you can use objects in expressions in just the same way that you use C++'s built-in data types. If you use the operator without providing the mechanism of how these operators are going to perform with the objects of our class, you will get error message

Fundamentals of Operator Overloading Process that enables C++’s operators to work with class objects. C++ has ability to provide the operators with a special meaning for a data. The mechanism of giving such special meanings to an operator is known as operator overloading. C++ can overload the entire C++ operator except following: 1. Class member access operator (. ) 2. Scope resolution operator (::) 3. Size operator (sizeof) 4. Conditional operator (? :) Why do we need operator overloading? Do we really need it? For instance, compare the following syntaxes to perform addition of two objects a and b of a user-defined class Fraction (assume class Fraction has a member function called add() which adds two Fraction objects): c = a.add (b); c = a+b; After overloading the appropriate operators, you can use objects in expressions in just the same way that you use C++'s built-in data types. If you use the operator without providing the mechanism of how these operators are going to perform with the objects of our class, you will get error message

Defining operator overloading operator function : Defines the operations that the overloaded operator will perform relative to the class upon which it will work. An operator function is created using the keyword operator. Operator functions can be either members or nonmembers of a class. Nonmember operator functions are almost always friend functions of the class. The way operator functions are written differs between member and nonmember functions. The general format of member operator function is: return type class name :: operator op(arglist) { function body // task defined }

Example: #include using namespace std; class Overload { public: int num; Overload() {num=0; } void operator*(); }; void Overload::operator*( ) { num*=num; cout<<"\n Num ="<<num; num+=1; } int main( ) { Overload obj; *obj; return 0; } OUTPUT: Num =0 Num = Process exited after seconds with return value 0 Press any key to continue...

#include using namespace std; class xyz{ int x, y, z; public: void get(){ cout<<"XYZ please\n"; cin>>x>>y>>z; } void disp(){ cout<<x<<y<<z<<endl; } friend void operator-(xyz &S);//pass by reference }; void operator-(xyz &S){ S.x=-S.x;//object name must be used as it is a friend function S.y=-S.y; S.z=-S.z; } int main(){ xyz s1; s1.get(); cout<<"BEFORE OVERLOADING\n"; s1.disp(); cout<<"AFTER OVERLOADING \n"; -s1; s1.disp(); return 0; } OUTPUT: XYZ please BEFORE OVERLOADING 456 AFTER OVERLOADING Process exited after seconds with return value 0 Press any key to continue...

Overloading Stream-Insertion and Stream-Extraction Operators Overloaded > operators –Overloaded to perform input/output for user-defined types –Left operand of types ostream & and istream & –Must be a non-member function because left operand is not an object of the class –Must be a friend function to access private data members Example: #include using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; }

Distance(int f, int i){ feet = f; inches = i; } friend ostream &operator<<( ostream &output, const Distance &D ) { output << "F : " << D.feet << " I : " << D.inches; return output; } friend istream &operator>>( istream &input, Distance &D ) { input >> D.feet >> D.inches; return input; } }; int main() { Distance D1(11, 10), D2(5, 11), D3; cout << "Enter the value of object : " << endl; cin >> D3; cout << "First Distance : " << D1 << endl; cout << "Second Distance :" << D2 << endl; cout << "Third Distance :" << D3 << endl; return 0; } OUTPUT: Enter the value of object : 45 6 First Distance : F : 11 I : 10 Second Distance :F : 5 I : 11 Third Distance :F : 45 I : Process exited after 5.81 seconds with return value 0 Press any key to continue...

Cont… Operators that cannot be overloaded..* :: ?: It is not possible to change the “arity” of an operator ie. The numbers of operands an operator takes. Overloaded unary operators remain unary operators and overloaded binary operators remain binary operators.

Cont… Operator overloading is not automatic Must write operator-overloading functions to perform the desired operations Call on an object of the class and operate on that object To use an operator on an object of a class, must define overloaded operator functions for that class 1. The assignment operator(=) may be used with most classes to perform memberwise assignment of the data members – each data member is assigned from the assignment’s “source”(on the right) object to the “target” object (on the left). Memberwise assignment is dangerous for classes with pointer members, so well’l explicitly overload the assignment operator for such classes The address (&) operator returns a pointer to the object; this operator also can be overloaded

Cont… The comma operator evaluates the expression to its left then the expression to its right, and returns the value of the latter expression. This operator also can be overloaded. The ability to provide the operators with a special meaning for a data type and this mechanism of giving such special meanings to an operator is known as operator overloading.

Cont… Syntax: Returntype classname::operator op(arg-list) { Functionbody // task defined } Where returntype is the type of value returned by the specified operation and op is the operator being overloaded. The op is preceded by the keyword operator. Operator op is the function name.

Cont… The process of overloading involves the following steps: 1. First, create a class that defines the datatype that is to be used in the overloading operation. 2.Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function. 3.Define the operator function to implement the required operations.

Overloading stream insertion and a stream extraction operators Fundamental types using the stream extraction operator>> Stream insertion operator<< The class libraries provide with c++ compilers overload these operators to process each fundamental type, including pointers and C- like char * strings. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types.

Cont… Example: #ifndef PHONE NUMBER_H #define PHONE NUMBER_H #include Using std::ostream; Using std::istream; #include Using std:: string;

Cont… Class phonenumber { Friend ostream &operator<<(ostream &, const phonenumber &); Friend istream &operator>>(istream&, phone number &); Private: string areacode; string exchange;

Cont… String line; }; *endif # phonenumber.cpp #overloaded stream insertion and stream extraction operators # for class phonenumber #include Using std::setw; #include “phonenumber.h”

Cont… //overloaded stream insertion operator; cannot be //a member function if we would like to invoke it with // cout << some phonnumber; Ostream &operator<<(ostream &output, const phonenumber &number) { output<<“(“ <<number.areacode<<“)” << number.exchange<<“_” <<number.line; return output; } Cin>> some phonnumber Istream &operator >> (istream &input, phonenumber &number)

Cont… { input.ignore(); input>>setw (3)>> number.areacode; input.ignore(2); input>>setw (3)>>number.exchange; input>>ignore(); input>>setw (4)>> number.line; Return input; }// end function operator>>

Cont… #include Using std :: cout; Using std :: cin; Using std :: endl; # include “phonenumber.h” Int main() { Phonenumber phone; Cout<<“enter phone number in the form (123) :”<<endl; Cin >>phone; Cout<<“The phone entered was:”; Cout<<phone invokes operator<< by implicitly issuing Cout<<phone<<endl; Return 0; } //end main

Cont… Output: Enter phone number in the form (123) : (800) The phone number entered was:(800)

Cont… Unary operators Op x or x Op Binary operators X op y Friend functions Operator op (x) Member functions Operator op (x.y)

Global and member operators Operators that are loaded as member functions (),[], -> any other assignment operators, the operator overloading function must be declared as a class member. For other operators, the operator overloading functions can be class members or global functions.

Cont… Operators as member functions and global functions When an operator function is implemented as a member function, the leftmost operand must be an object(or a reference to an object) of the operator’s class.

Overloading stream-insertion and stream –extraction operators The overloaded stream insertion operator(<<) is used in an expression in which the left operand has type ostream &, as in cout<< class object. To use the operator, the right operand is an object of a user –defined class, it must be overloaded as a global function. For a member function operator << have to be a member of the ostream class. Istream &,as in cin>> class object and the right operand is an abject of a user-defined class – it must be a global function.

Cont… Is able to input and output the fundamental types using the stream extraction operator>> and the stream insertion operator<<. The class libraries provided with compiler overload these operators to process each fundamental type, including pointers and strings The stream insertion and stream extraction operators also can be overloaded to perform input and output for user defined types.

Cont… Example: # include (iostream> # include Class phonenumber { friend ostream &operator<<(ostream &,const phonenumber &); friend istream &operator>>(istream &, phonenumber & ); Private: string areacode; string exchange; string line; }; #endif

Overloading unary operators A unary operator for a class can be overloaded as a non static member function with no arguments or as a global function with one argument That argument must be either an object of the class or a reference to an object of the class. Example: Class string { Public: bool operator!() const; ….. };

Overloading binary operators A binary operator can be overloaded as a non – static member function with one argument or as a global function with two arguments(one of those arguments must be either a class object or a reference to a class object). Class string Public: bool operator<(const stsring &)const; … };

Cont… Example: unary operator # include Class space { Int x; Int y; Int z; Public: Void getdata(int a, int b, int c); Void display (void); Void operator-(); // overload unary minus }; Void space :: getdata(int a, int b, int c) { x = a; y = b; z = c; }

Cont… Void space :: display (void) { cout << x<<“”; cout<< y <<“”; cout<< z<< “\n”; } Void space :: operator-() //defining operator-() { X = -x; Y = -y; Z = -z; } Main() { space s; s.getdata(10, -20, 30); cout << “s : “; s.display(); -s; //activates operator –() Cout<<“S : “ ; S.Display (); } Output: S : S :

Cont… Example : Over loading Binary operators: # include Class complex { float x; //real part float y; // Imaginary part Public: complex () complex(float real, float imag} [ x= real; y=imag;] complex operator+(complex); void display (void); }; Complex complex :: operator + (complex c) { Complex temp; //temporary temp.x = x + c.x; //float addition temp.y = y + c.y; //float addition return (temp);

Cont… Void complex :: display (void) { cout<<x<< “ + j” <<y<<“\n”; } Main() { complex C1,C2,C3; C1 = complex (2.5, 3.5); C2 = complex (1.6, 2.7); C3 = C1 + C2; cout << “ C1 = “ ; C1.display(); cout<< “ C2 = “ ; C2.display(); cout<< “ C3 = “; C3. display(); } Output C1 = j3.5 C2 = j2.7 C3 = j6.2