Developed By : Ms. K. S. Kotecha

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 Fundamentals
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.
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.
Type Conversions. 2 When different types of variables are mixed in an expression, C applies automatic type conversion to the operands The type of data.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
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
Operator Overloading Customised behaviour of operators Unit - 06.
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.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
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.
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.
OPERATOR OVERLOADING Customised behaviour of operators.
CONSTRUCTOR AND DESTRUCTORS
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
Unit VI polymorphism. Md.Jaffar Sadiqsumalatha Polymorphism refers to : one name, many forms. Polymorphism is of two types:  Compile time polymorphism.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Operator Overloading.
Chapter 18 - C++ Operator Overloading
CSE1002 – Problem Solving with Object Oriented Programming
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.
Constructors and Destructors
Operator Overloading Ritika Sharma.
Chapter 13: Overloading and Templates
Chapter 14: More About Classes.
C++ Templates.
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
Constructor & Destructor
Chapter 15: Overloading and Templates
Operator Overloading BCA Sem III K.I.R.A.S.
Chapter 14: More About Classes.
Operator Overloading
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
Dr. Bhargavi Dept of CS CHRIST
Constructors and Destructors
Operator overloading Dr. Bhargavi Goswami
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++
Java Programming Language
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Lecture 7.
Operator overloading Friend Function This Operator Inline Function
Presentation transcript:

Developed By : Ms. K. S. Kotecha OOMP Operator Overloading Developed By : Ms. K. S. Kotecha

Need of Operator Overloading OOMP Classes And Objects Introduction Need of Operator Overloading Overloading assignment Binary and Unary Operators Overloading using friends Rules for Operator Overloading Type Conversions

Introduction What is overloading OOMP Introduction What is overloading – Overloading means assigning multiple meanings to a function name or operator symbol – It allows multiple definitions of a function with the same name, but different signatures. C++ supports – Function overloading – Operator overloading

OOMP Operator Overloading “Operator overloading is the ability to tell the compiler how to perform a certain operation when its corresponding operator is used on one or more variables.”

void swap(int&, int&) //swap version– 1 OOMP Function Overloading void swap(int&, int&) //swap version– 1 void swap(Date&, Date&) //swap version– 2 main() { int i, j; Date a, b; swap( i, j ); //swap version – 1 applied swap( a, b ); //swap version – 2 applied }

Overloaded Constructors OOMP Overloaded Constructors class Account { double balance; double rate; public: Account(); Account( double bal ); Account( double bal, double pcnt); … }; main() { Account a1; Account a2(12000, 0.8); }

Need Of Operator Overloading OOMP Need Of Operator Overloading Operator overloading provides a convenient notation for manipulating user-defined objects with conventional operators.

Overloadable Operators OOMP Overloadable Operators arithmetic, logical, relational operators call (), subscript [], de-reference -> assignment and initialization explicit and implicit type conversion operators

OOMP Operator Overloading Overloading of operators are achieved by creating operator function. “An operator function defines the operations that the overloaded operator can perform relative to the class”. An operator function is created using the keyword operator.

Operator Function Definitons OOMP Operator Function Definitons Two ways: Implemented as member functions Implemented as non-member or Friend functions the operator function may need to be declared as a friend if it requires access to protected or private data

Oveloadable /Non-Overloadable Operators OOMP Oveloadable /Non-Overloadable Operators Overloadable + - * / % ^ & | ~ ! = < > <= >= += -= *= ++ -- << >> == != && || /= %= ^= &= |= *= <<= >>= [ ] ( ) -> ->* new delete etc. Non-overloadabale :: .* . ?:

Operator Functions Unary ++, --, &, *, +, -, ~, !, OOMP Operator Functions Unary ++, --, &, *, +, -, ~, !, Arithmetic +, -, *, /, % Shift <<, >>, Relational >, <, >=, <=, ==, != Bitwise &, ^, | Logical &&, || Assignment =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=, Data Access [], ->, ->* Function call() Comma , Storage new,new[],delete,delete[],

Operator Overloading Within Class: ret-type operator#(argument-list); OOMP Operator Overloading Creating a Member Operator Function Within Class: ret-type operator#(argument-list); Outside Class: ret-type class-name::operator#(arg-list) { // operations }

Operator Function Definitons OOMP Operator Function Definitons Defined as a member function class Complex { ... public: Complex operator +(Complex &op) { real = real + op._real, imag = imag + op._imag; return(Complex(real, imag)); } };

Operator Overloading ob1 = ob1 + ob2; ob1 = ob1.operator+ (ob2); OOMP Operator Overloading Implicitly passed by this pointer Explicitly passed argument ob1 = ob1 + ob2; ob1 = ob1.operator+ (ob2);

How does it work? OOMP “John Johnson” name CStr first(“John”); CStr last(“Johnson”); CStr name(first+last); CStr CStr::operator+(CStr str1,CStr str2) { CStr new_string(str1); new_string.cat(str2.get()); return new_string; } “John Johnson” name Copy constructor Temporary CStr object

Operator Function Definitons OOMP Operator Function Definitons Defined as a friend function class Complex { ... public: double real() { return _real; } double imag() { return _imag; } friend Complex operator+(Complex, Complex) }; c = a+b; c = operator+ (a, b); Complex operator +(Complex &op1, Complex &op2) { real = op1.real + op2.real, imag = op1.imag + op2.imag; return (Complex(real, imag)); }

Operator Functions as Class Members vs. as friend Functions OOMP Member vs non-member Operator functions can be member or non-member functions When overloading ( ), [ ], -> or any of the assignment operators, must use a member function Operator functions as member functions Leftmost operand must be an object (or reference to an object) of the class If left operand of a different type, operator function must be a non-member function Operator functions as non-member functions Must be friends if needs to access private or protected members Enable the operator to be commutative

Unary Operators OOMP class UnaryExample { private: int m_LocalInt; public: UnaryExample(int j) m_LocalInt = j; } int operator++ () return (m_LocalInt++); };

UnaryExample object1(10); OOMP Unary Operators void main() { UnaryExample object1(10); cout << object1 ++; // overloaded operator called }

Binary Operators OOMP class BinaryExample { private: int m; public: BinaryExample(int j) m = j; } int operator+ (BinaryExample& rhsObj) m = m + rhsObj.m; return m; } };

BinaryExample object1(10), object2(20); OOMP Binary Operators void main() { BinaryExample object1(10), object2(20); cout << object1 + object2; // overloaded operator }

Rules for Operator Overloading OOMP Rules for Operator Overloading Only existing operators can be overloaded. New operators cannot be created. The overloaded operator must have at least one operand that is of user-defined type. We cannot change the basic meaning of an operator. Overloaded operators follow the syntax rules of the original operators. Operator functions cannot have default arguments.

Restrictions on Operator Overloading OOMP Overloading restrictions Precedence of an operator cannot be changed Associativity of an operator cannot be changed Arity (number of operands) cannot be changed Unary operators remain unary, and binary operators remain binary Operators &, *, + and - each have unary and binary versions Unary and binary versions can be overloaded separately No overloading operators for built-in types Cannot change how two integers are added Produces a syntax error

Rules for Operator Overloading OOMP Rules for Operator Overloading The following operators that cannot be overloaded: sizeof Size of operator . Membership operator .* Pointer-to-member operator : : Scope resolution operator ? ; Conditional operator

Rules for Operator Overloading OOPCGL Rules for Operator Overloading The following operators can be over loaded with the use of member functions and not by the use of friend functions: Assignment operator = Function call operator( ) Subscripting operator [ ] Class member access operator -> Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument.

Rules for Operator Overloading OOMP Rules for Operator Overloading Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class. Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments.

Program for Implementation OOMP Program for Implementation Pgm to create a class Matrix assuming its properties and add two matrices by overloading + operator. Read and display the matrices by overloading input(>>) & output(<<) operators respectively. Pgm to create a class RATIONAL with numerator and denominator as properties and perform following operations on rational numbers. - r = r1 * r2; (by overloading * operator) - To check equality of r1 and r2 (by overloading == operator)

Overloading = Prototype: classname& operator =(classname & obj); OOMP Overloading = Prototype: classname& operator =(classname & obj); Example: A & operator =(const A& obj) { m = obj.m; return * this; } void main() { A ob1( 10) ,ob2 ; : ob2 = ob1; }

Overloading >> Prototype: OOMP Overloading >> Prototype: friend istream& operator >>(istream&, Matrix&); Example: istream& operator >>(istream& in, Matrix& m) { for(int i=0; i<row*col; i++) in >> m[i]; } return in; void main() { : Cin>>mobj; }

Overloading << Prototype: OOMP Overloading << Prototype: friend ostream& operator <<(ostream&, Matrix&); Example: ostream& operator <<(ostream& out, Matrix& m) { for(int i=0; i<row; ++i) for(int j=0; j<col; j++) { out>> m[i][j] >> “\t” ; } out << endl; } void main() { : cout<<mobj; }

We must design the conversion routines by ourselves. OOMP Type Conversions The type conversions are automatic only when the data types involved are built-in types. int m; float x = 3.14159; m = x; // convert x to integer before its value is assigned // to m. For user defined data types, the compiler does not support automatic type conversions. We must design the conversion routines by ourselves.

Different situations of data conversion between incompatible types. OOMP Type Conversions Different situations of data conversion between incompatible types. Conversion from basic type to class type. Conversion from class type to basic type. Conversion from one class type to another class type.

Basic type to Class Type OOMP Basic type to Class Type class time { int hrs ; int mins ; public : … time (int t) { hrs = t / 60 ; mins = t % 60; } } ; void main () { int duration = 85; time T1(duration) ; // time t1 = duration; }

Class type to Basic Type OOMP Class type to Basic Type A constructor function do not support type conversion from a class type to a basic type. An overloaded casting operator is used to convert a class type data to a basic type. It is also referred to as conversion function. operator typename( ) { … … ( function statements ) } This function converts a class type data to typename.

Class type to Basic Type OOMP Class type to Basic Type vector : : operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } This function converts a vector to the square root of the sum of squares of its components. The casting operator function should satisfy the following conditions: It must be a class member. It must not specify a return type. It must not have any arguments.

Class type to Basic Type OOMP Class type to Basic Type Conversion functions are member functions and it is invoked with objects. Therefore the values used for conversion inside the function belong to the object that invoked the function. This means that the function does not need an argument. vector v1; double d = v1;

One Class type to Other Class Type OOMP One Class type to Other Class Type objX = objY ; // objects of different types objX is an object of class X and objY is an object of class Y. The class Y type data is converted to the class X type data and the converted value is assigned to the objX. Conversion is takes place from class Y to class X. Y is known as source class. X is known as destination class.

One Class type to Other Class Type OOMP One Class type to Other Class Type Conversion between objects of different classes can be carried out by either a constructor or a conversion function. Choosing of constructor or the conversion function depends upon where we want the type-conversion function to be located in the source class or in the destination class.

OOMP What are Containers? A Container is a data structure whose main purpose is to store and retrieve a large number of values Containers are abstract data types (ADTs) that hold values. They don't change the content – only hold it so that it can be retrieved later. Items in Containers are referred to by special objects called: iterators.

OOMP What are Containers? These data structure permits storage and retrieval of data items independent of content. The two fundamental operations of any container are:   Put(C,x): Insert a new data item x into the container C. Get(C): Retrieve the next item from the container C. Different types of containers support different retrieval orders, based on insertion order or position.

OOMP Types of Containers The STL consists of 10 container classes categorized according to the ordering of the elements and the different types of operations that access the data Sequence Containers: store data by position in linear order, 1st, 2nd, 3rd, etc. Associative Containers: store elements by key e.g. name, ssn, part numbers etc. A program accesses an element in an associative container by its key, which may bear no relationship to the location of the element in the container Adaptor Containers: contain other containers as their underlying storage structure.

Associative Containers OOMP Containers Sequence Containers Adapter Containers Associative Containers Vector Stack Set, Multiset Deque Queue Map, Mutltimap List Priority Queue Trees Hash