Operation Overloading.

Similar documents
Operation Overloading.

Object-Oriented Design (OOD) and C++

More Advanced Class Concepts

Program construction in C++ for Scientific Computing

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Operators & Expressions

Overloading Operators in C++

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

Operators. Lecture 12 Section Robb T. Koether. Hampden-Sydney College. Fri, Feb 9, 2018

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Instantiation of Template class

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Ch. 12: Operator Overloading

Overloading & Polymorphism

Module Operator Overloading and Type Conversion. Table of Contents

Overloaded Operators, Functions, and Students

Friends and Unary Operators

by Pearson Education, Inc. All Rights Reserved.

Ch 8. Operator Overloading, Friends, and References

CS105 C++ Lecture 7. More on Classes, Inheritance

11.2. Overloading Operators

Chapter 18 - C++ Operator Overloading

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Infix to Postfix Conversion

C++ Important Questions with Answers

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

(7-2) Operator Overloading D & D Chapter 10. Instructor - Andrew S. O Fallon CptS 122 (February 23, 2018) Washington State University

Object Oriented Programming with c++ Question Bank

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operator Overloading

Operator Overloading in C++ Systems Programming

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE

Lecture 3 ADT and C++ Classes (II)

Roxana Dumitrescu. C++ in Financial Mathematics

7.1 Optional Parameters

Operators in C. Staff Incharge: S.Sasirekha

3. Java - Language Constructs I

Absolute C++ Walter Savitch

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Programming in C++ 6. Floating point data types

C++ Programming Chapter 7 Pointers

Information Science 1

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

CS304 Object Oriented Programming Final Term

B.C.A 2017 OBJECT ORIENTED PROGRAMMING USING C++ BCA303T MODULE SPECIFICATION SHEET

UNIT- 3 Introduction to C++

Review of the C Programming Language

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

Programming for Engineers: Operators, Expressions, and Statem

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

ISA 563 : Fundamentals of Systems Programming

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Chapter 3: Operators, Expressions and Type Conversion

CS11 Intro C++ Spring 2018 Lecture 5

Operator overloading. Instructor: Bakhyt Bakiyev

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Expressions and Assignment Statements

Review of the C Programming Language for Principles of Operating Systems

A Simple Syntax-Directed Translator

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

A <Basic> C++ Course

Problem Solving with C++

Chapter 9. Operator Overloading. Dr Ahmed Rafat

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Generalized Constant Expressions

A <Basic> C++ Course

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

SECTION II: LANGUAGE BASICS

Informatics Ingeniería en Electrónica y Automática Industrial

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Information Science 1

Chapter 7. Expressions and Assignment Statements

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

W3101: Programming Languages C++ Ramana Isukapalli

Programming in C++ 5. Integral data types

CS201 Some Important Definitions

Objectives. In this chapter, you will:

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

The Decaf Language. 1 Lexical considerations

MaanavaN.Com CS1203 OBJECT ORIENTED PROGRAMMING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

C/C++ Programming Lecture 7 Name:

Unit 3. Operators. School of Science and Technology INTRODUCTION

OBJECT ORIENTED PROGRAMMING USING C++

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

Chapter 11: More About Classes and Object-Oriented Programming

Fundamentals of Programming Session 7

2 ADT Programming User-defined abstract data types

Evolution of Programming Languages

Transcription:

Operation Overloading pm_jat@daiict.ac.in

Recap: Why do we need Operator Overloading? Operator based expressions are more readable: Compare a + b * c with plus(a, times(b, c))

Recap: What is Operator Overloading? Some different thoughts to understand- It is making of your class an operator aware, or making the operator aware of that class It is means of giving new meaning to an operator in certain context of usage Basically you define how the operator should behave if it is used with particular type of operand(s)

Recap: What is Operator Overloading? Suppose you have two complex objects c1 and c2, and want to express, their addition as : c1 + c2 The operation is add two operands c1 and c2, and type of left and right operands are complex objects Compiler is not able to resolve this operation till it is able to find such operation definition Since this is your class, you need to provide definition for this operation on this class objects

Some operators not necessarily need to be defined There are two operators that will work with user defined objects, even if you do not define any function for- The assignment operator (=) The assignment operator will do a member wise assignment of the data members of the class. The address operator (&) The address operator simply returns the address of the object in memory.

Source: Big C++, Page 605 Operators, you can overload

Operator Overloading Note that You can not redefine existing behavior of an operator You can not change precedence, associativity, or arity of an operator You can not invent new operator symbols

Recap: How do you overload an operator? Two ways: Define a global function or define a member function of the class. Define a global function named operator+ (to overload plus operator), have first parameter of type of left operand and second parameter as type of right operand (in most case type of both are going to be same) Though, here, you can have parameters by value; you should have const references

Recap When you have this function defined, and you write expression: c1 + c2 Compiler interprets this expression as function call operator+(c1, c2) The function Implementation defines actions that needs to be performed when such expression encounters

Operator Member function When define operator+ as member function, and write expression: c1 + c2 Then, the compiler would interprets it as function call c1.operator+(c2)

How compiler looks appropriate function for binding When you write expression: a + b Compiler attempts to translate this expression to a function call and binds it to appropriate function definition. First, compiler looks for a member function operator+ in class A, if finds, then translates above expression to a.operator+(b) If not then looks for a global function operator+, having two parameters of type A and B respectively, if finds then translates expression a+b to operator+(a,b) If still does not find; compiler raises error: no match for 'operator+' in a + b'

Operator Overloading Note that when you have operator overloading as member function, the function has only one parameter, that is right operand; object on which method is being invoked becomes left operand Whether you implement as global function or a member function, usage syntax remains same: a + b Which approach to follow?

Which approach to be followed? Following things needs to be kept in mind while deciding about it. A global function may not able to access private members of operand objects; however you can permit a global function to access private data of a class by making the function friend of the class However granting access is violation of basic encapsulation principles, and not a good object oriented design; Therefore, if private part is to be accessed, it should be implemented as a member function of the class If no access of private members are required then either is fine.

Similarly you can overload other operators overloaded for Complex Class Exercise: implement some more operators for Complex class Subtract: - Multiplication: * Add and Update: += Equality: ==

Some Operator Functions needs to be member function only For example function for overloading [], ->, = operators. This is to ensure that their first operand is lvalue

Overloading Assignment (=) operator Though not required for complex class; let us do, just to see how it is done. What should be the prototype for overloading assignment operator for Complex Class? Why return is required? Is returning reference OK?

Overloading Input >> and Output << Though, originally shift operators Almost always overloaded for I/O operations Overloaded exactly as the binary arithmetic operators Should be overloaded as global functions?

Extraction/Insertion operator concepts All following expression mean same, where, let us say a, and b are objects of some classcin >> a >> b; ((cin >> a ) >> b); operator>>(operator>>(cin, a), b); Assuming that, we define a global function, following is typical prototype of extraction operationistream& operator>>(istream&, T&); Similarly for insertionostream& operator<<(ostream&, const T&);

overloading >> operator To overload >> operator for complex class, define following function istream& operator>>(istream&, Complex&);. istream& operator>>(istream& in, Complex& c) { double r, i; in >> r >> i; c.set(r,i); return in; }

We have already seen how this function is called?. operator>>(cin, a); operator>>(cin, b); Or operator>>(operator>>(cin, a), b); Or (cin >> a ) >> b); Or cin >> a >> b;

overloading >> operator Note that we have implemented it as a global function approach The function can not access private part of the complex class in this function To enable it to access private part, make the function as friend of the class.

Make a function friend to allow a global function to access private part of the class

overloading >> operator You can not overload >> operator as member function of a class. Why? Recall that, in member function approach, left operand is object of the class for which the function is being defined; In the case of, cin >> a; left operand is object of istream class? And you can not add a function operator>>(complex&) to istream class!!

Complex Class definition

Complex Class Implementation

Complex class : a typical client code

Overloading Unary Arithmetic Operators Operators + - & * have both binary and unary forms To overload unary form, reduce the number of parameters by one For example Complex operator-(const Complex& c) { } Complex tmp(-c.getreal(), -c.getimag()); return tmp; A unary operator defined as a member function takes no arguments

Overload = operator for Student class Needs to overload because, it requires deep copying. However you can have added functionality that when you assign one student object to another, Id of target object does not get over-written

What Next? See how other operators are overloaded, typically Increment ++ /decrement -- operators Subscript [] operator Overloading Conversion (cast) Operators More interesting examples, Chapter-17, Big C++

Thanks