SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Unit - III

Operator Overloading
Customised behaviour of operators
Unit Introduction
This unit covers operator overloading
Unit Objectives







After covering this unit you will understand…
Operator overloading
Different types of operator and their
overloading
Operators that cannot be overloaded
Inheritance and overloading
Automatic type conversion
Introduction


Operator overloading








Enabling C++’s operators to work with class
objects
Using traditional operators with user-defined
objects
Requires great care; when overloading is misused,
program difficult to understand
Examples of already overloaded operators





4

Operator << is both the stream-insertion operator and
the bitwise left-shift operator
+ and -, perform arithmetic on multiple types

Compiler generates the appropriate code based on
the manner in which the operator is used


Overloading an operator
Write function definition as normal
 Function name is keyword operator followed by
the symbol for the operator being overloaded
 operator+ used to overload the addition
operator (+)




Using operators


To use an operator on a class object it must be
overloaded unless the assignment operator(=)or
the address operator(&)
Assignment operator by default performs memberwise
assignment
 Address operator (&) by default returns the address of an
object


5
Restrictions on Operator Overloading



Operators that can be overloaded
C++ operators that can be overloaded
+

*

/

%

^

&

|

~

!

=

<

>

+=

-=

*=

/=

%=

^=

&=

|=

<<

>>

>>=

<<=

==

!=

<=

>=

&&

||

++

--

->*

,

->

[]

()

new

delete

new[]



-

delete[]

C++ Operators that cannot be overloaded
Operators that cannot be overloaded
.

6

.*

::

?:

sizeof
Restrictions on Operator Overloading






7

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 new operators can be created
 Use only existing operators
No overloading operators for built-in types
 Cannot change how two integers are added
 Produces a syntax error
Operator Functions as Class
Members vs. as friend Functions






8

Member vs non-member
 In general, 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
Overloading Stream-Insertion and Stream-Extraction
Operators


Overloaded << and >> operators
Overloaded to perform input/output for userdefined 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


9
Overloading Unary Operators


Overloading unary operators
Can be overloaded with no arguments or one
argument
 Should usually be implemented as member functions






Avoid friend functions and classes because they
violate the encapsulation of a class

Example declaration as a member function:
class String {
public:
bool operator!() const;
...
};

10
Overloading Unary Operators


Example declaration as a non-member function
class String {
friend bool operator!( const
String & )
...
}

11
Overloading Binary Operators


Overloaded Binary operators
Non-static member function, one argument
 Example:


class Complex {
public:
const Complex operator+ (
const Complex &);
...
};

12
Overloading Binary Operators
Non-member function, two arguments
 Example:


class Complex {
friend Complex operator +(
const Complex &, const Complex &
);
...
};

13
Example: Operator Overloading
class OverloadingExample
{
private:
int m_LocalInt;
public:
OverloadingExample(int j) // default constructor

{
m_LocalInt = j;
}
int operator+ (int j) // overloaded + operator

{
return (m_LocalInt + j);
}
};
Example: Operator Overloading (contd.)
void main()
{
OverloadingExample object1(10);
cout << object1 + 10; // overloaded operator called
}
Types of Operator


Unary operator



Binary operator
Unary Operators


Operators attached to a single operand (-a, +a, -a, a--, ++a, a++)
Example: Unary Operators
class UnaryExample
{
private:
int m_LocalInt;
public:
UnaryExample(int j)

{
m_LocalInt = j;
}
int operator++ ()

{
return (m_LocalInt++);
}
};
Example: Unary Operators (contd.)
void main()
{
UnaryExample object1(10);
cout << object1++; // overloaded operator results in value
// 11
}
Unary Overloaded Operators -- Member Functions


Invocation in Two Ways -- Object@ (Direct) or Object.operator@() (As a
Function)
class number{
int n;
public:
number(int x = 0):n(x){};
number operator-(){return number (-n);}
};
main()
{
number a(1), b(2), c, d;
//Invocation of "-" Operator -- direct
d = -b; //d.n = -2
//Invocation of "-" Operator -- Function
c = a.operator-(); //c.n = -1
}
20
Binary Overloaded Operators -- Member Functions


Invocation in Two Ways -- ObjectA @ ObjectB (direct) or
ObjectA.operator@(ObjectB) (As a Function)
class number{
int n;
public:
number(int x = 0):n(x){};
number operator+(number ip)
{return number (ip.n + n);}
};
main()
{
number a(1), b(2), c, d;
//Invocation of "+" Operator -- direct
d = a + b; //d.n = 3
//Invocation of "+" Operator -- Function
c = d.operator+(b); //c.n = d.n + b.n = 5
}
21
Binary Operators


Operators attached to two operands (a-b, a+b,
a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b)
Example: Binary Operators
class BinaryExample
{
private:
int m_LocalInt;
public:
BinaryExample(int j)

{
m_LocalInt = j;
}
int operator+ (BinaryExample& rhsObj)

{
return (m_LocalInt + rhsObj.m_LocalInt);
}
};
Example: Binary Operators (contd.)
void main()
{
BinaryExample object1(10), object2(20);
cout << object1 + object2; // overloaded operator called
}
Non-Overloadable Operators


Operators that can not be overloaded due to
safety reasons:
Member Selection ‘.’ operator
 Member dereference ‘.*’ operator
 Exponential ‘**’ operator
 User-defined operators
 Operator precedence rules









Operator Overloading and Inheritance
An operator is overloaded in super class but
not overloaded in derived class is called nonmember operator in derived class
In above, if operator is also overloaded in
derived class it is called member-operator
= ( ) [ ] –> –>* operators must be member
operators
Other operators can be non-member
operators
Automatic Type Conversion




Automatic type conversion by the C++
compiler from the type that doesn’t fit, to the
type it wants
Two types of conversion:
Constructor conversion
 Operator conversion

Constructor Conversion




Constructor having a single argument of another
type, results in automatic type conversion by the
compiler
Prevention of constructor type conversion by
use of explicit keyword
Example: Constructor Conversion
class One
{
public:
One() {}
};
class Two
{
public:
Two(const One&) {}
};
void f(Two) {}
void main()
{
One one;
f(one); // Wants a Two, has a One
}
Operator Conversion








Create a member function that takes the current
type
Converts it to the desired type using the
operator keyword followed by the type you
want to convert to
Return type is the name of the operator
overloaded
Reflexivity - global overloading instead of
member overloading; for code saving
Example: Operator Conversion
class Three
{
int m_Data;
public:
Three(int ii = 0, int = 0) : m_Data(ii) {}
};
class Four
{
int m_Data;
public:
Four(int x) : m_Data(x) {}
operator Three() const
{
return Three(m_Data);
}
};
void g(Three) {}
Example: Operator Conversion (contd.)
void main()
{
Four four(1);
g(four);
g(1); // Calls Three(1,0)
}
Type Conversion Pitfalls


Compiler performs automatic type conversion
independently, therefore it may have the
following pitfalls:
Ambiguity with two classes of same type
 Automatic conversion to more than one type - fanout
 Adds hidden activities (copy-constructor etc)

Unit Summary






In this unit you have covered …
Operator overloading
Different types of operator
Operators that cannot be overloaded
Inheritance and overloading
Automatic type conversion

Weitere ähnliche Inhalte

Was ist angesagt?

Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversionsAmogh Kalyanshetti
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 
Command line arguments
Command line argumentsCommand line arguments
Command line argumentsAshok Raj
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variablessangrampatil81
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2MOHIT TOMAR
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++Sujan Mia
 

Was ist angesagt? (20)

Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversions
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 

Ähnlich wie Operator overloading

Ähnlich wie Operator overloading (20)

Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Oops
OopsOops
Oops
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
OOPS-Seminar.pdf
OOPS-Seminar.pdfOOPS-Seminar.pdf
OOPS-Seminar.pdf
 
c++
c++c++
c++
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Cpp (C++)
Cpp (C++)Cpp (C++)
Cpp (C++)
 
Operator Overloading in C++
Operator Overloading in C++Operator Overloading in C++
Operator Overloading in C++
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 
Operator overloading (binary)
Operator overloading (binary)Operator overloading (binary)
Operator overloading (binary)
 
NIKUL SURANI
NIKUL SURANINIKUL SURANI
NIKUL SURANI
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
 
Overloading
OverloadingOverloading
Overloading
 
OOP_UnitIII.pdf
OOP_UnitIII.pdfOOP_UnitIII.pdf
OOP_UnitIII.pdf
 

Mehr von Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devicesKumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithmsKumar
 
region-filling
region-fillingregion-filling
region-fillingKumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivationKumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons dericationKumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xsltKumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xmlKumar
 
Xml basics
Xml basicsXml basics
Xml basicsKumar
 
XML Schema
XML SchemaXML Schema
XML SchemaKumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xmlKumar
 
Applying xml
Applying xmlApplying xml
Applying xmlKumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLKumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee applicationKumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLKumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB FundmentalsKumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programmingKumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EEKumar
 

Mehr von Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Kürzlich hochgeladen

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Kürzlich hochgeladen (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Operator overloading

  • 1. Unit - III Operator Overloading Customised behaviour of operators
  • 2. Unit Introduction This unit covers operator overloading
  • 3. Unit Objectives      After covering this unit you will understand… Operator overloading Different types of operator and their overloading Operators that cannot be overloaded Inheritance and overloading Automatic type conversion
  • 4. Introduction  Operator overloading     Enabling C++’s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is misused, program difficult to understand Examples of already overloaded operators    4 Operator << is both the stream-insertion operator and the bitwise left-shift operator + and -, perform arithmetic on multiple types Compiler generates the appropriate code based on the manner in which the operator is used
  • 5.  Overloading an operator Write function definition as normal  Function name is keyword operator followed by the symbol for the operator being overloaded  operator+ used to overload the addition operator (+)   Using operators  To use an operator on a class object it must be overloaded unless the assignment operator(=)or the address operator(&) Assignment operator by default performs memberwise assignment  Address operator (&) by default returns the address of an object  5
  • 6. Restrictions on Operator Overloading  Operators that can be overloaded C++ operators that can be overloaded + * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[]  - delete[] C++ Operators that cannot be overloaded Operators that cannot be overloaded . 6 .* :: ?: sizeof
  • 7. Restrictions on Operator Overloading    7 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 new operators can be created  Use only existing operators No overloading operators for built-in types  Cannot change how two integers are added  Produces a syntax error
  • 8. Operator Functions as Class Members vs. as friend Functions    8 Member vs non-member  In general, 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
  • 9. Overloading Stream-Insertion and Stream-Extraction Operators  Overloaded << and >> operators Overloaded to perform input/output for userdefined 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  9
  • 10. Overloading Unary Operators  Overloading unary operators Can be overloaded with no arguments or one argument  Should usually be implemented as member functions    Avoid friend functions and classes because they violate the encapsulation of a class Example declaration as a member function: class String { public: bool operator!() const; ... }; 10
  • 11. Overloading Unary Operators  Example declaration as a non-member function class String { friend bool operator!( const String & ) ... } 11
  • 12. Overloading Binary Operators  Overloaded Binary operators Non-static member function, one argument  Example:  class Complex { public: const Complex operator+ ( const Complex &); ... }; 12
  • 13. Overloading Binary Operators Non-member function, two arguments  Example:  class Complex { friend Complex operator +( const Complex &, const Complex & ); ... }; 13
  • 14. Example: Operator Overloading class OverloadingExample { private: int m_LocalInt; public: OverloadingExample(int j) // default constructor { m_LocalInt = j; } int operator+ (int j) // overloaded + operator { return (m_LocalInt + j); } };
  • 15. Example: Operator Overloading (contd.) void main() { OverloadingExample object1(10); cout << object1 + 10; // overloaded operator called }
  • 16. Types of Operator  Unary operator  Binary operator
  • 17. Unary Operators  Operators attached to a single operand (-a, +a, -a, a--, ++a, a++)
  • 18. Example: Unary Operators class UnaryExample { private: int m_LocalInt; public: UnaryExample(int j) { m_LocalInt = j; } int operator++ () { return (m_LocalInt++); } };
  • 19. Example: Unary Operators (contd.) void main() { UnaryExample object1(10); cout << object1++; // overloaded operator results in value // 11 }
  • 20. Unary Overloaded Operators -- Member Functions  Invocation in Two Ways -- Object@ (Direct) or Object.operator@() (As a Function) class number{ int n; public: number(int x = 0):n(x){}; number operator-(){return number (-n);} }; main() { number a(1), b(2), c, d; //Invocation of "-" Operator -- direct d = -b; //d.n = -2 //Invocation of "-" Operator -- Function c = a.operator-(); //c.n = -1 } 20
  • 21. Binary Overloaded Operators -- Member Functions  Invocation in Two Ways -- ObjectA @ ObjectB (direct) or ObjectA.operator@(ObjectB) (As a Function) class number{ int n; public: number(int x = 0):n(x){}; number operator+(number ip) {return number (ip.n + n);} }; main() { number a(1), b(2), c, d; //Invocation of "+" Operator -- direct d = a + b; //d.n = 3 //Invocation of "+" Operator -- Function c = d.operator+(b); //c.n = d.n + b.n = 5 } 21
  • 22. Binary Operators  Operators attached to two operands (a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b)
  • 23. Example: Binary Operators class BinaryExample { private: int m_LocalInt; public: BinaryExample(int j) { m_LocalInt = j; } int operator+ (BinaryExample& rhsObj) { return (m_LocalInt + rhsObj.m_LocalInt); } };
  • 24. Example: Binary Operators (contd.) void main() { BinaryExample object1(10), object2(20); cout << object1 + object2; // overloaded operator called }
  • 25. Non-Overloadable Operators  Operators that can not be overloaded due to safety reasons: Member Selection ‘.’ operator  Member dereference ‘.*’ operator  Exponential ‘**’ operator  User-defined operators  Operator precedence rules 
  • 26.     Operator Overloading and Inheritance An operator is overloaded in super class but not overloaded in derived class is called nonmember operator in derived class In above, if operator is also overloaded in derived class it is called member-operator = ( ) [ ] –> –>* operators must be member operators Other operators can be non-member operators
  • 27. Automatic Type Conversion   Automatic type conversion by the C++ compiler from the type that doesn’t fit, to the type it wants Two types of conversion: Constructor conversion  Operator conversion 
  • 28. Constructor Conversion   Constructor having a single argument of another type, results in automatic type conversion by the compiler Prevention of constructor type conversion by use of explicit keyword
  • 29. Example: Constructor Conversion class One { public: One() {} }; class Two { public: Two(const One&) {} }; void f(Two) {} void main() { One one; f(one); // Wants a Two, has a One }
  • 30. Operator Conversion     Create a member function that takes the current type Converts it to the desired type using the operator keyword followed by the type you want to convert to Return type is the name of the operator overloaded Reflexivity - global overloading instead of member overloading; for code saving
  • 31. Example: Operator Conversion class Three { int m_Data; public: Three(int ii = 0, int = 0) : m_Data(ii) {} }; class Four { int m_Data; public: Four(int x) : m_Data(x) {} operator Three() const { return Three(m_Data); } }; void g(Three) {}
  • 32. Example: Operator Conversion (contd.) void main() { Four four(1); g(four); g(1); // Calls Three(1,0) }
  • 33. Type Conversion Pitfalls  Compiler performs automatic type conversion independently, therefore it may have the following pitfalls: Ambiguity with two classes of same type  Automatic conversion to more than one type - fanout  Adds hidden activities (copy-constructor etc) 
  • 34. Unit Summary      In this unit you have covered … Operator overloading Different types of operator Operators that cannot be overloaded Inheritance and overloading Automatic type conversion