23
Operator Operator Overloading Overloading Customised behaviour of Customised behaviour of operators operators Chapter: Chapter: 08 08 Lecture: 28 Lecture: 28 Date: 25.09.2012 Date: 25.09.2012

Lec 28 - operator overloading

Embed Size (px)

Citation preview

Page 1: Lec 28 - operator overloading

Operator Operator OverloadingOverloadingCustomised behaviour of Customised behaviour of

operatorsoperators

Chapter: Chapter: 0808

Lecture: 28Lecture: 28

Date: 25.09.2012Date: 25.09.2012

Page 2: Lec 28 - operator overloading

ObjectivesObjectives Overloading in C++Overloading in C++

Function overloadingFunction overloading Operator overloadingOperator overloading

Different types of operators and their Different types of operators and their overloadingoverloading

Operators that cannot be overloadedOperators that cannot be overloaded Data conversionData conversion

Automatic type conversionAutomatic type conversion User-defined type conversionUser-defined type conversion

Page 3: Lec 28 - operator overloading

C++ C++ OverloadingOverloading

Overloading in C++ allows to specify more than Overloading in C++ allows to specify more than one definition for a one definition for a functionfunction name or an name or an operatoroperator in the same scope, which is called in the same scope, which is called function function overloadingoverloading and and operator overloadingoperator overloading respectively.respectively.

An An overloaded declarationoverloaded declaration is the one that had been is the one that had been declared with exactly the same name as the declared with exactly the same name as the previous declaration in the same scope, except that previous declaration in the same scope, except that both declarations have different arguments and both declarations have different arguments and also different definition (implementation).also different definition (implementation).

Function

Operator

C++ OVERLAODING

Page 4: Lec 28 - operator overloading

C++ Function C++ Function OverloadingOverloading

An overloaded function can have multiple An overloaded function can have multiple definitions for the same function name in the definitions for the same function name in the same scope. same scope.

The definition of the function must differ from The definition of the function must differ from each other by the each other by the typestypes and/or the and/or the number of number of argumentsarguments in the argument list. in the argument list.

Function declarations cannot be overloaded if Function declarations cannot be overloaded if they differ only by return type.they differ only by return type.

Page 5: Lec 28 - operator overloading
Page 6: Lec 28 - operator overloading

C++ Operator C++ Operator OverloadingOverloading

It simplifies the program listing, e.g.,It simplifies the program listing, e.g.,

d3.addobjects(d1, d2)d3.addobjects(d1, d2)

or the similar but equally obscureor the similar but equally obscure

d3 = d1.addobjects(d2)d3 = d1.addobjects(d2)

can be changed to much more readable formcan be changed to much more readable form

d3 = d1 + d2d3 = d1 + d2 Operator overloading refers to giving normal Operator overloading refers to giving normal

C++ operators such as +, *, and <= so on, an C++ operators such as +, *, and <= so on, an additional meaning additional meaning when they are applied to when they are applied to user defined data types, e.g., user defined data types, e.g.,

d3 = d1 + d2 d3 = d1 + d2 (legal when d1, d2, and d3 are (legal when d1, d2, and d3 are basic types)basic types)

Page 7: Lec 28 - operator overloading

C++ Operator C++ Operator Overloading Overloading (Syntax)(Syntax)

returnTypereturnType operator*( operator*(parametersparameters););

any type keyword operator symbolany type keyword operator symbol

Return type Return type may be whatever the may be whatever the operator returnsoperator returns Including a reference to the object of the Including a reference to the object of the

operandoperand

Operator symbol Operator symbol may be any valid may be any valid operator allowed by the language operator allowed by the language compiler (see the following list)compiler (see the following list)

Page 8: Lec 28 - operator overloading

Operators that cannot be overloaded

. .* :: ?:

Operators that can be overloaded

+ - * / % ^

& | ~ ! = <

> += -= *= /= %=

^= &= |= << >> >>=

<<= == != <= >= &&

|| ++ -- ->* , ->

[] () new delete new[] delete[]

Page 9: Lec 28 - operator overloading

Types of OperatorsTypes of Operators

OPERATORSOPERATORS

Unary

Binary(+, <, =, …)

Prefix(!, & , ~ , …)

Postfix(++, --, …)

Page 10: Lec 28 - operator overloading

Unary OperatorsUnary Operators

Operators attached to a single Operators attached to a single operand,operand,

e.g., -a, +a, --a, a--, ++a, a++e.g., -a, +a, --a, a--, ++a, a++

Page 11: Lec 28 - operator overloading

Example: Unary Example: Unary Operators Operators (Prefix)(Prefix)

class UnaryExampleclass UnaryExample

{ private:{ private:

int m_LocalInt;int m_LocalInt;

public:public:

UnaryExample(int j)UnaryExample(int j)

{ m_LocalInt = j;{ m_LocalInt = j; }}

int operator++ () int operator++ ()

{ return (++m_LocalInt);{ return (++m_LocalInt); }}

};};

int main()int main()

{ UnaryExample object1(10);{ UnaryExample object1(10);

cout << ++object1; cout << ++object1; // overloaded operator// overloaded operator

getch(); getch();

return 0;return 0;

}}

Page 12: Lec 28 - operator overloading

Example: Unary Example: Unary Operators Operators (Postfix)(Postfix)

class UnaryExampleclass UnaryExample

{ private:{ private:

int m_LocalInt;int m_LocalInt;

public:public:

UnaryExample(int j)UnaryExample(int j)

{ m_LocalInt = j;{ m_LocalInt = j; }}

int operator++ (int operator++ (intint) ) // “int” argument for postfix // “int” argument for postfix operatoroperator

{ return { return m_LocalInt++; }m_LocalInt++; }

};};

int main()int main()

{ UnaryExample object1(10);{ UnaryExample object1(10);

cout << object1++; cout << object1++; // overloaded operator// overloaded operator

getch(); getch();

return 0;return 0;

}}

Page 13: Lec 28 - operator overloading

Binary OperatorsBinary Operators

Operators attached to two operands,Operators attached to two operands,

e.g.,e.g.,

a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a-b, a+b, a*b, a/b, a%b, a>b, a>=b,

a<b, a<=b, a==ba<b, a<=b, a==b

Page 14: Lec 28 - operator overloading

Example: Binary Example: Binary OperatorsOperatorsclass BinaryExample class BinaryExample

{{

private:private:

int m_LocalInt;int m_LocalInt;

public:public:

BinaryExample(int j) BinaryExample(int j)

{ m_LocalInt = j;{ m_LocalInt = j; } }

int operator+ (BinaryExample& rhsObj)int operator+ (BinaryExample& rhsObj)

{ return (m_LocalInt + rhsObj.m_LocalInt); }{ return (m_LocalInt + rhsObj.m_LocalInt); }

};};

int main()int main()

{ BinaryExample object1(10), object2(20);{ BinaryExample object1(10), object2(20);

cout << object1 + object2; cout << object1 + object2; // overloaded operator called// overloaded operator called

getch();getch();

return 0;return 0;

}}

Page 15: Lec 28 - operator overloading

Non-Overloadable Non-Overloadable OperatorsOperators

Operators that cannot be overloaded Operators that cannot be overloaded due to safety reasons:due to safety reasons: Member Selection ‘.’ operatorMember Selection ‘.’ operator Member dereference ‘.*’ operatorMember dereference ‘.*’ operator Exponential ‘**’ operatorExponential ‘**’ operator User-defined operatorsUser-defined operators Operator precedence rulesOperator precedence rules

Page 16: Lec 28 - operator overloading

Data ConversionData Conversion Assignment operator assigns a value Assignment operator assigns a value

from one side to another, e.g., from one side to another, e.g.,

intvar1 = intvar2intvar1 = intvar2 But what happens when the variables on But what happens when the variables on

different sides of the = sign are of different sides of the = sign are of different types?different types?

Two possibilities:Two possibilities: Automatic data conversionAutomatic data conversion User-defined data conversionUser-defined data conversion

Page 17: Lec 28 - operator overloading

Conversion Between Conversion Between basic Typesbasic Types#include<iostream>

#include<conio.h>using namespace std;

int main(){int intvar;float floatvar;

intvar = static_cast<int>(floatvar); //casting provides //casting provides explicit conversionexplicit conversion

getch();return 0;}

Page 18: Lec 28 - operator overloading

Conversion between Conversion between User-defined and Basic User-defined and Basic

TypesTypes Built-in conversion routines can’t be Built-in conversion routines can’t be

relied while converting b/w user-defined relied while converting b/w user-defined data types and basic types; since the data types and basic types; since the compiler doesn’t know anything about compiler doesn’t know anything about user-defined types besides what we tell it.user-defined types besides what we tell it.

Page 19: Lec 28 - operator overloading

Create a member function that takes the current Create a member function that takes the current type type

Converts it to the desired type using the Converts it to the desired type using the operatoroperator keyword followed by the type you want keyword followed by the type you want to convert to.to convert to.

Return type is the Return type is the namename of the operator of the operator overloadedoverloaded

Reflexivity - global overloading instead of Reflexivity - global overloading instead of member overloading; for code saving.member overloading; for code saving.

Syntax:Syntax:

operator type_name()operator type_name()

{{ }}

Conversion between Conversion between User-defined and Basic User-defined and Basic

TypesTypes

Page 20: Lec 28 - operator overloading

Con

vers

ion

Betw

een

C-S

trin

g a

nd

S

trin

g O

bje

cts

Page 21: Lec 28 - operator overloading

Lecture SummaryLecture Summary

Lecture covered …Lecture covered … Overloading in C++Overloading in C++

Function overloadingFunction overloading Operator overloadingOperator overloading

Different types of operatorDifferent types of operator Operators that cannot be overloadedOperators that cannot be overloaded Data conversion:Data conversion:

Automatic type conversionAutomatic type conversion User-defined type conversionUser-defined type conversion

Page 22: Lec 28 - operator overloading

Lecture SummaryLecture Summary

Lectures, books and so on will be updated Lectures, books and so on will be updated at:at:

http://www.itquest.tk/ http://www.itquest.tk/ (http://www.itquest.ucoz.com/) (http://www.itquest.ucoz.com/)

http://http://www.downloadbooks.mytestproject.co.cc/www.downloadbooks.mytestproject.co.cc/

Page 23: Lec 28 - operator overloading

Class InheritanceClass Inheritance