Operator overloading Dr. Bhargavi Goswami

Slides:



Advertisements
Similar presentations
Operator Overloading Fundamentals
Advertisements

Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Chapter 13: Overloading.
Chapter 15: Operator Overloading
Operator overloading Object Oriented Programming.
Operator Overloading in C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
Operator Overloading and Type Conversions
Chapter 12: Adding Functionality to Your Classes.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4.
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 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.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
More C++ Features True object initialisation
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.
Learners Support Publications Constructors and Destructors.
Programming with ANSI C ++
Operator Overloading.
Yan Shi CS/SE 2630 Lecture Notes
Constructors and Destructors
Operator Overloading Ritika Sharma.
Chapter 13: Overloading and 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
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Programming with ANSI C ++
Developed By : Ms. K. S. Kotecha
Object-Oriented Programming (OOP) Lecture No. 21
Constructor & Destructor
Class: Special Topics Copy Constructors Static members Friends this
Chapter 15: Overloading and Templates
Operator Overloading BCA Sem III K.I.R.A.S.
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Operator Overloading
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Operator Overloading; String and Array Objects
Inheritance Dr. Bhargavi Goswami Department of Computer Science
Advanced Program Design with C++
Operator Overloading; String and Array Objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
Dr. Bhargavi Dept of CS CHRIST
Constructors and destructors
Constructors and Destructors
Pointers Dr. Bhargavi Goswami Department of Computer Science
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++
Data Structures and Algorithms Introduction to Pointers
Java Programming Language
INTERNATIONAL INSTITUTE OF IFORMATION TECHNOLOGY, (I²IT)
Operator Overloading; String and Array Objects
Chapter 6 Polymorphism.
CS410 – Software Engineering Lecture #5: C++ Basics III
A Deeper Look at Classes
Class: Special Topics 2 For classes using memory allocation
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Operator overloading Dr. Bhargavi Goswami Department of Computer Science CHRIST Bangalore. bhargavigoswami@gmail.com 9426669020

Operator overloading Has enhanced the power of extensibility of C++. Allows user defined datatype behave same as built-in datatypes. Eg. A = B + C Operator overloading provides operators an additional specific meaning for data types. What does operator overloading do? It provides flexible option for creation of new definition for C++ operators. Why word overload? Because it provides additional meaning.

Operators that cannot be overloaded Class member access operators . .* Scope Resolution operator :: Size of operator (sizeof) Conditional operator ?:

Operators that can be overloaded + - * / % & | ~ ! , < > <= >= ++ << >> == != && += -= /= %= ^= |= *= <<= >>= [] ->* new new[] delete delete[]

Operator overloading syntax Semantics of the operator gets extended, but we cannot change its syntax, precedence, grammatical rules, its basic behavior. So, when operator is overloaded, its originality is not lost. Eg. + operator which used to add two integers, can be extended to add two vectors. How to achieve operator overloading? Using special function called operator function. Below syntax, op is the operator overloaded, operator is a keyword. Syntax:

Operator overloading functions and types Operator function must be eitheir member functions (nonstatic) or friend function. What is the difference? Friend function takes one argument for unary operators, two for binary. But, member function has zero argument for unary operators and one for binary. Why so? Object that invokes member function is passed implicitly to member function. But, for friend function, both the arguments has to be passed explicitly. Note: Arguments may be passed either by value or by reference.

Some prototypes:

Process of overloading Create a class Define data type and return type of operator function Declare operator function <op()> in public section as member function or friend function. Define the body of operator function. How to invoke? Eg. X++ --X X+Y We will see the things in detail in programs.

Unary operator overloading Takes one operand. Eg. –x. changes sign of x. Lets do the same thing to object to convert all data items to negative. Eg. 7-1-UnaryMinus.cpp Remember, nothing it returns so statements like following will not work. S2 = -S1; Y we passed argument by reference in friend function? As operator overloading function returns nothing, it will not reflect the change back to object for printing values. So, pass by reference is necessary.

Binary operator overloading Can we replace ‘c = sum(a,b);’ with ‘c=a+b;’ ? Yes. Using binary operator overloading. See next fig. Eg. 7-2-binaryMultiply.cpp Eg. 7-2-BinaryPlusOverloading.cpp It does following: 1. receives one argument of type complex 2. returns type complex 3. itself is member function of complex What invokes function in c3=c1+c2? C1+ Then what is c2? Argument passed to function. Then what is c3? It catches returned value of operator overloading function. Alternative? Usual call statement such as: C3 = c1.operator+(c2) Thus, left hand operand invokes operator function and right hand operand is passed as an argument to operator function.

Can we avoid declaration of temp object? Yes. How? By using constructor. if we want to avoid using temp object, use constructor: return complex ((x+c.x),(y+c.y)); It initializes an object with no name. Returns the content by copying back to obj Such obj are temporary objects which gets destroyed no sooner values are provided to other object. Exercise: try out replacing temp object creation using constructor.

Overloading operators using friends Only requirement is that friend function needs all operands passed as arguments. What is the need? When one operand is object and one operand is basic data type, it may not work. Eg. A = 2 + B; or A = a * B; // a is int variable Y? Because left hand operator is not object but a normal int or normal built in int variable. Limitation of member function?. Yes. Then solution? Friend function can handle all the three situation. i.e. A = 2 + B; A = a + B; A = A + B; How? By passing first argument as built in data type and second data type as user defined data type. Eg. 7-3-InputOutputOperatorOverloadingFriend.cpp

Manipulation of strings using operators How C implement strings? Ans: By character array. Drawback? Programmer has to determine length of string before using it and allocate memory likewise. C++ removes this limitation? (Yes/No) Ans: Not completely. But, to great extend. How? Ans: By string class. Discussed in detail in Ch.15. Self Study: Example Program 7.4.

Other operator overloading Subscript operator [] Pointer to Member opeartor -> Lets check both the examples. Eg. 7-5-overloadingSubscriptOperator.cpp and 7-6-overloadingPointer2MemberOperator.cpp

Rules for overloading operators Only existing operators can be overloaded. New operators cannot be overloaded. The overloaded operator must have at least one operand that is of user defined type. Overloaded operator follow the syntax rules of original operator. Operators can be overloaded but cannot be overridden. All operators are not overloaded, few exemptions exist. (See next fig) We cannot use friend function for few operators. (See next fig)

Operators cannot be overloaded with friend

Rules for overloading operators Unary operator: Takes no explicit argument until it is a friend function. Binary operator: Takes one explicit argument and if it is a friend, takes two. For binary operator, left hand operator must be always object and never a value. For binary operator as a friend, left hand operator can be a value. Binary arithmetic operators such as +,-,*,/ must explicitly return a value. Binary arithmetic operators must not make attempt to change own arguments.

Type Conversions C applies automatic type conversion. Assignment operator “ = ” automatic type conversion. Eg. int m; float x = 3.145; m = x; This converts x to int automatically. Everything is fine till datatype is built in. What happens when datatype is user defined? Eg. V3 = V1 + V2 //all are class objects.

Type Conversions Situations which may need type conversion: Basic to Class Class to Basic Class to Class First is achieved by constructors and functions. Second is achieved with cascading operator. Conditions: It must be a class member. It must not specify a return type. It must not have any arguments. Third one is achieved by either constructor or conversion function.

Basic to class We are already doing it using constructors and functions. Eg. Constructor body: A(int x){ a = b = x;}

Class to basic Using casting operators. What? const_cast<type> (expr) performs explicitly override const of same type. dynamic_cast<type> (expr) performs runtime cast that verifies the validity of the cast. reinterpret_cast<type> (expr) performs casting of pointer to any other type of pointer. static_cast<type> (expr) performs cast a base class pointer into a derived class pointer. Eg. Vector operator double() { double sum=0; for (int i=0;i<size;i++) sum = sum + v[i] * v[i]; return sum; } double length = double (V1) OR double length = V1; HERE, V1 is object of Vector class.

Class to class Happens with constructors or functions. X objx; //X is a class Y objy; //Y is a class Eg: objx = objy; So class Y is source data type and class X is destination data type. See next figure.

Object conversion

remember:

Type Conversions Compiler does not support automatic type conversations for user defined data types. We can use casting operator functions to achieve this. The casting operator function should satisfy following conditions: It must be a class member. It must not specify return type. It must not have any argument. Lets check the example. Eg. 7-7-dataConversionOperatorOverloading.cpp

Thank you. See u soon. Explore more about the topic. Chapter 7 is over. Thank you. See u soon.