SlideShare a Scribd company logo
1 of 20
1
Operator overloading
• Services are obtained from objects by sending
messages i.e. function call
• This function call is cumbersome for certain
kinds of classes e.g. mathematical classes
• For example, statements like
– d3.addobjects(d1, d2);
or
– d3 = d1.addobjects(d2);
• can be changed to the much more readable
– d3 = d1 + d2;
2
Cont.
• Operator overloading refers to giving the
normal C++ operators, such as +, *, <=, and
etc., additional meanings when they are
applied to user-defined data types
• Operator overloading gives you the
opportunity to redefine the C++ language
– By using classes to create new kinds of variables,
– operator overloading to create new definitions for
operators
3
Examples of c++ overloaded operator
• Addition + and subtraction – operator
 +, – operators perform differently, depending on their
context in integer arithmetic, floating-point arithmetic
and pointer arithmetic.
• Stream insertion (<<) and extractor (>>) operator
(cout<< and cin>>)
 << is used both as the stream insertion operator and
as the bitwise left-shift operator
 >> is used both as the stream extraction operator and
as the bitwise right-shift operator
 <<, >> are overloaded in the C++ Standard Library std
4
Fundamentals of Operator Overloading
• Jobs performed by overloaded operators can also
be performed by explicit function calls
• Programmers can use operators with user-
defined types
• C++ does not allow new operators to be created
• It does allow most existing operators to be
overloaded so that, when these operators are
used with objects
• This is a powerful capability
5
Cont.
• An operator is overloaded by writing a non-static
member function definition
• Function name becomes the keyword operator
followed by the symbol for the operator being
overloaded
– E.g. operator + () { …. }
• Function name operator+ would be used to
overload the addition operator (+)
• Assignment operator (=) may be used with every
class to perform member wise assignment of the
data members
– d1 = d2;
6
Restrictions on Operator Overloading
Operators that can be overloaded
Operators that cannot be overloaded
• Attempting to overload a non overloadable
operator is a syntax error
7
Precedence, Associativity and No. of
Operands
• Precedence means which operator to solve
first (+, -, *, /, = )
• The precedence of an operator cannot be
changed by overloading
• The associativity of an operator cannot be
changed by overloading
• Overloaded unary operators (++, --) remain
unary operators
• overloaded binary operators remain binary
operators
8
Creating New Operators
• It is not possible to create new operators
• only existing operators can be overloaded
– E.g. ** can be used for exponential in some
programming languages
– ** is not in the list od existing operator so it
cannot be overloaded
• Attempting to create new operators via
operator overloading is a syntax error
9
Operators for Fundamental Types
• The meaning of how an operator works on
fundamental types cannot be changed by
operator overloading
• For example, programmer cannot change the
meaning of how + adds two integers
• Operator overloading works only with
– objects of user-defined types or
– a mixture of an object of a user-defined type and
an object of a fundamental type
10
Examples
• c1++; or c1--;
– Overloading ++ and -- unary operator
• dist3 = dist1 + dist2;
– Overloading assignment and addition binary
operator
– It does not mean that += is also overloaded for
Distance objects
• dist1+= dist2; or dist1-=dist2
11
Overloading Unary Operators
• Examples of unary operators are the increment and
decrement operators ++ and --, and the unary minus,
as in -33
• Counter class example
– To keep track of a count.
– Objects of that class were increment the count
value by calling a member function:
c1.inc_count();
• But it would be more readable if we could have used
the increment operator ++
++c1;
12
Example
class Counter{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{ return count; }
void operator ++ (){ //increment (prefix)
++count;
}
};
Program Output
main(){
Counter c1, c2;
cout << “nc1=” << c1.get_count();
cout << “nc2=” << c2.get_count();
++c1; ++c2; ++c2;
cout << “nc1=” << c1.get_count();
cout << “nc2=” << c2.get_count() << endl;
}
c1=0
c2=0
c2=2
c1=1
13
The operator Keyword
• The keyword operator is used to overload the
++ operator
void operator ++ ()
• The return type (void in this case) comes first,
followed by the keyword operator, followed
by the operator itself (++), and finally the
argument list enclosed in parentheses
• This declarator syntax tells the compiler to call
this member function whenever the ++
operator is encountered
14
Cont.
• The compiler can distinguish between
overloaded functions in the following ways
– data types of arguments and
– the number of their arguments
• The only way a compiler can distinguish
between overloaded operators is by looking at
the data type of their operands.
– If the operand is a basic type such as an int then
the compiler will use its built-in routine to
increment an int
15
Operator Arguments
• the ++ operator is applied to a specific object,
as in the expression ++c1
• What does this operator increment?
• It increments the count data in the object of
which it is a member
• Since member functions can always access the
particular object for which they’ve been
invoked, this operator requires no arguments
16
Operator Return Values
• The operator++() function has a defect. You will
discover it if you use a statement like this in main():
c1 = ++c2;
• The compiler will complain. Why
• Because ++ operator is defined to have a return type
of void in the operator++() function, while in the
assignment statement it is being asked to return a
variable of type Counter
• The normal ++ operator, applied to basic data types
such as int, would not have this problem
int x,y; y=10; x = y ++;
17
class Counter{
unsigned int count;
public:
Counter() : count(0)
{ }
unsigned int get_count()
{ return count; }
Counter operator ++ (){
++count;
Counter temp;
temp.count = count;
return temp;
}
};
Counter class Example
main()
{
Counter c1, c2;
cout << “nc1=” << c1.get_count();
cout << “nc2=” << c2.get_count();
++c1;
c2 = ++c1;
cout << “nc1=” << c1.get_count();
cout << “nc2=” << c2.get_count() ;
}
0
count
c1
0
count
c2
1 2
2
Program Output
c1=0
c2=0
c2=2
c1=2
18
Nameless Temporary Objects
main()
{
Counter c1, c2;
cout << “nc1=” << c1.get_count();
cout << “nc2=” << c2.get_count();
++c1;
c2 = ++c1;
cout << “nc1=” << c1.get_count();
cout << “nc2=” << c2.get_count() ;
}
class Counter{
unsigned int count;
public:
Counter() : count(0)
{ }
Counter(int c) : count(c)
{ }
unsigned int get_count()
{ return count; }
Counter operator ++ (){
++count;
return Counter(count);
}
};
Counter temp;
temp.count = count;
return temp;
19
Postfix Notation
• So far we’ve seen the increment operator
used only in its prefix form.
++c1
• What about postfix, where the variable is
incremented after its value is used in the
expression?
c1++
20
Counter class Example
class Counter{
private:
unsigned int count;
public:
Counter() : count(0)
{ }
Counter(int c) : count(c)
{ }
unsigned int get_count() const
{ return count; }
Counter operator ++ (){
return Counter(++count);
}
Counter operator ++ (int){
return Counter(count++);
}
};
main(){
Counter c1, c2;
cout << “c1=” << c1.get_count();
cout << “c2=” << c2.get_count();
++c1; c2 = ++c1;
cout << “c1=” << c1.get_count();
cout << “c2=” << c2.get_count();
c2 = c1++;
cout << “c1=” << c1.get_count();
cout << “c2=” << c2.get_count() ;
}
0
count
c1
0
count
c2
1
2 2
Program Output
c1=0
c2=0
c2=2
c1=2
++c1;
c2 = ++c1;
c2 = c1++;
2
3 c2=2
c1=3

More Related Content

Similar to Week7a.pptx

Similar to Week7a.pptx (20)

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
C++ process new
C++ process newC++ process new
C++ process new
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 

Recently uploaded

The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

Week7a.pptx

  • 1. 1 Operator overloading • Services are obtained from objects by sending messages i.e. function call • This function call is cumbersome for certain kinds of classes e.g. mathematical classes • For example, statements like – d3.addobjects(d1, d2); or – d3 = d1.addobjects(d2); • can be changed to the much more readable – d3 = d1 + d2;
  • 2. 2 Cont. • Operator overloading refers to giving the normal C++ operators, such as +, *, <=, and etc., additional meanings when they are applied to user-defined data types • Operator overloading gives you the opportunity to redefine the C++ language – By using classes to create new kinds of variables, – operator overloading to create new definitions for operators
  • 3. 3 Examples of c++ overloaded operator • Addition + and subtraction – operator  +, – operators perform differently, depending on their context in integer arithmetic, floating-point arithmetic and pointer arithmetic. • Stream insertion (<<) and extractor (>>) operator (cout<< and cin>>)  << is used both as the stream insertion operator and as the bitwise left-shift operator  >> is used both as the stream extraction operator and as the bitwise right-shift operator  <<, >> are overloaded in the C++ Standard Library std
  • 4. 4 Fundamentals of Operator Overloading • Jobs performed by overloaded operators can also be performed by explicit function calls • Programmers can use operators with user- defined types • C++ does not allow new operators to be created • It does allow most existing operators to be overloaded so that, when these operators are used with objects • This is a powerful capability
  • 5. 5 Cont. • An operator is overloaded by writing a non-static member function definition • Function name becomes the keyword operator followed by the symbol for the operator being overloaded – E.g. operator + () { …. } • Function name operator+ would be used to overload the addition operator (+) • Assignment operator (=) may be used with every class to perform member wise assignment of the data members – d1 = d2;
  • 6. 6 Restrictions on Operator Overloading Operators that can be overloaded Operators that cannot be overloaded • Attempting to overload a non overloadable operator is a syntax error
  • 7. 7 Precedence, Associativity and No. of Operands • Precedence means which operator to solve first (+, -, *, /, = ) • The precedence of an operator cannot be changed by overloading • The associativity of an operator cannot be changed by overloading • Overloaded unary operators (++, --) remain unary operators • overloaded binary operators remain binary operators
  • 8. 8 Creating New Operators • It is not possible to create new operators • only existing operators can be overloaded – E.g. ** can be used for exponential in some programming languages – ** is not in the list od existing operator so it cannot be overloaded • Attempting to create new operators via operator overloading is a syntax error
  • 9. 9 Operators for Fundamental Types • The meaning of how an operator works on fundamental types cannot be changed by operator overloading • For example, programmer cannot change the meaning of how + adds two integers • Operator overloading works only with – objects of user-defined types or – a mixture of an object of a user-defined type and an object of a fundamental type
  • 10. 10 Examples • c1++; or c1--; – Overloading ++ and -- unary operator • dist3 = dist1 + dist2; – Overloading assignment and addition binary operator – It does not mean that += is also overloaded for Distance objects • dist1+= dist2; or dist1-=dist2
  • 11. 11 Overloading Unary Operators • Examples of unary operators are the increment and decrement operators ++ and --, and the unary minus, as in -33 • Counter class example – To keep track of a count. – Objects of that class were increment the count value by calling a member function: c1.inc_count(); • But it would be more readable if we could have used the increment operator ++ ++c1;
  • 12. 12 Example class Counter{ private: unsigned int count; //count public: Counter() : count(0) //constructor { } unsigned int get_count() //return count { return count; } void operator ++ (){ //increment (prefix) ++count; } }; Program Output main(){ Counter c1, c2; cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count(); ++c1; ++c2; ++c2; cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count() << endl; } c1=0 c2=0 c2=2 c1=1
  • 13. 13 The operator Keyword • The keyword operator is used to overload the ++ operator void operator ++ () • The return type (void in this case) comes first, followed by the keyword operator, followed by the operator itself (++), and finally the argument list enclosed in parentheses • This declarator syntax tells the compiler to call this member function whenever the ++ operator is encountered
  • 14. 14 Cont. • The compiler can distinguish between overloaded functions in the following ways – data types of arguments and – the number of their arguments • The only way a compiler can distinguish between overloaded operators is by looking at the data type of their operands. – If the operand is a basic type such as an int then the compiler will use its built-in routine to increment an int
  • 15. 15 Operator Arguments • the ++ operator is applied to a specific object, as in the expression ++c1 • What does this operator increment? • It increments the count data in the object of which it is a member • Since member functions can always access the particular object for which they’ve been invoked, this operator requires no arguments
  • 16. 16 Operator Return Values • The operator++() function has a defect. You will discover it if you use a statement like this in main(): c1 = ++c2; • The compiler will complain. Why • Because ++ operator is defined to have a return type of void in the operator++() function, while in the assignment statement it is being asked to return a variable of type Counter • The normal ++ operator, applied to basic data types such as int, would not have this problem int x,y; y=10; x = y ++;
  • 17. 17 class Counter{ unsigned int count; public: Counter() : count(0) { } unsigned int get_count() { return count; } Counter operator ++ (){ ++count; Counter temp; temp.count = count; return temp; } }; Counter class Example main() { Counter c1, c2; cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count(); ++c1; c2 = ++c1; cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count() ; } 0 count c1 0 count c2 1 2 2 Program Output c1=0 c2=0 c2=2 c1=2
  • 18. 18 Nameless Temporary Objects main() { Counter c1, c2; cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count(); ++c1; c2 = ++c1; cout << “nc1=” << c1.get_count(); cout << “nc2=” << c2.get_count() ; } class Counter{ unsigned int count; public: Counter() : count(0) { } Counter(int c) : count(c) { } unsigned int get_count() { return count; } Counter operator ++ (){ ++count; return Counter(count); } }; Counter temp; temp.count = count; return temp;
  • 19. 19 Postfix Notation • So far we’ve seen the increment operator used only in its prefix form. ++c1 • What about postfix, where the variable is incremented after its value is used in the expression? c1++
  • 20. 20 Counter class Example class Counter{ private: unsigned int count; public: Counter() : count(0) { } Counter(int c) : count(c) { } unsigned int get_count() const { return count; } Counter operator ++ (){ return Counter(++count); } Counter operator ++ (int){ return Counter(count++); } }; main(){ Counter c1, c2; cout << “c1=” << c1.get_count(); cout << “c2=” << c2.get_count(); ++c1; c2 = ++c1; cout << “c1=” << c1.get_count(); cout << “c2=” << c2.get_count(); c2 = c1++; cout << “c1=” << c1.get_count(); cout << “c2=” << c2.get_count() ; } 0 count c1 0 count c2 1 2 2 Program Output c1=0 c2=0 c2=2 c1=2 ++c1; c2 = ++c1; c2 = c1++; 2 3 c2=2 c1=3