SlideShare a Scribd company logo
Unit4 Operator overloading
Presented By : Tekendra Nath Yogi
Tekendranath@gmail.com
College Of Applied Business And Technology
Introduction
• C++ provides a rich collection of operators(e.g., +, -, /, *….etc). Such
operators are used with the fundamental types(int, float, char,…..etc).
– E.g., int a, b, c; a= b+c is perfectly valid
• But if we try to use these operators directly with user defined types (e.g.,
objects) compiler will produce error.
– E.g., if a, b, c are objects of user defined class then the statement a = b+c is
not valid
• So to use operators with objects we need to overload operators (i.e.,
Customizes the C++ operators for operands of user-defined types.).
– E,g, a= b+c can be made valid by using overloading.
2By: Tekendra Nath Yogi
Contd..
• What is operator overloading?
– The mechanism of giving special meanings to an operator is called
operator overloading.
– i.e., redefine the way operator behaves so that we can use them
with user-defined types.
– Although the semantics of an operator can be extended, we can not
change its syntax and semantics that govern its use such as the
number of operand, precedence and associativity.
• E.g., For example, the operator + should be overloaded for addition, not
subtraction.
3By: Tekendra Nath Yogi
Contd..
• Syntax:
– operator overloading is done with the help of special function, called the
operator function. The general form of operator function is as follows:
4By: Tekendra Nath Yogi
Contd..
• Example:
– To add two objects of type distance each having a data members feet of
type int and inches of type float, we can over load + operator as follows:
5By: Tekendra Nath Yogi
General rules(Restrictions) for operator overloading
• We can not invent new operators that do not exist in the
language.
• i.e., only existing operator in the language can be overloaded.
– E.g., @ is not a valid c++ operator and can not be overloaded
6By: Tekendra Nath Yogi
Contd..
• Overloaded operator must follow the same syntax:
– E.g., if x and y are objects of a user defined class then
• X++12; // not allowed: ++ is not a binary operator
• X++; is allowed
• %x ; is not allowed: % is not an unary operator
• Y= x%3; is allowed
• One can not change the number of operand used by the operator.
• Try to overload operator where they make sense.
7By: Tekendra Nath Yogi
Contd..
• We can not change the way an operator works between native
c++ types.
– E.g ., we can not change how works between a double and an integer
variable.
– But we can change the working of operator for user defined types.
8By: Tekendra Nath Yogi
Contd..
• We can not change the operator precedence rules.
• i.e., the order of operator evaluation remains unchanged.
9By: Tekendra Nath Yogi
Contd..
• We can not change the operator associativity rules.
– E.g., the unary minus(-) operator associates from right to left.
x= -y; // unary minus associates from right to left
x = y-; // we can not alter unary minus to go from left to right.
10By: Tekendra Nath Yogi
Contd..
• Overloading some operators does not implicitly define other
operators for us.
– E.g., overloading the + and = operators for a class does not mean that the
+= operator is overloaded automatically for us. We will need to write
overload code for the += operator as well.
11By: Tekendra Nath Yogi
Contd..
• The overloaded operator must have at least one operand that is of
user-defined type.
• When overloading an operator using a member function:
• The leftmost operand of the overloaded operator must be an object of
the class type.
• The leftmost operand becomes the implicit parameter. All other
operands become function parameter.
12By: Tekendra Nath Yogi
Contd..
• Almost any operator can be overloaded in C++. However there
are few operator which can not be overloaded. Operator that
are not overloaded are follows
– scope operator (::)
– sizeof
– member selector –(.)
– member pointer selector (.*)
– ternary operator (?:)
13By: Tekendra Nath Yogi
Overloading Unary operator
• The operators which acts upon only one operand are called unary
operators.
• The following is a list of unary operator that can be overloaded in c++:
– Unary minus(-)
– Unary plus(+)
– Ones complement(~)
– Pointer dereference(*)
– Not (!)
– Increment operator(++)
– Decrement operator(--)
14By: Tekendra Nath Yogi
Contd..
• Prefix(++, --) and postfix (++. --)unary operator overloading:
– Increment operators increase the value of operand by 1, while decrement
operators(--) decrease value of operand by 1.
– They can be written either before the operand or after it. Depending on its
location, they can be classified as either prefix operators or postfix
operators.
– If the increment and decrement operators are written before the operand,
then they are termed as prefix operators. However, if they are written after
the operand, then they are termed as postfix operators.
15By: Tekendra Nath Yogi
Contd..
16By: Tekendra Nath Yogi
Contd..
• Overloading prefix increment operator:
17By: Tekendra Nath Yogi
Contd..
18By: Tekendra Nath Yogi
Contd..
• Overloading prefix decrement operator:
19By: Tekendra Nath Yogi
Contd..
20By: Tekendra Nath Yogi
Contd..
• Class work: WAP to overload prefix operator as shown above use
parameterized constructor to initialize the value of data member
count.
21By: Tekendra Nath Yogi
Contd..
• Overload postfix increment operator:
22By: Tekendra Nath Yogi
Contd..
23By: Tekendra Nath Yogi
Contd..• Overload postfix decrement operator:
24By: Tekendra Nath Yogi
Contd..
25By: Tekendra Nath Yogi
• Returning values from operator function: Returning values using temporary
objects:
26By: Tekendra Nath Yogi
Contd..
27By: Tekendra Nath Yogi
Contd..
• Returning values using nameless temporary objects:
28By: Tekendra Nath Yogi
Contd..
29By: Tekendra Nath Yogi
Overloading Binary Operators
• Binary operator are operators, which require two operands to perform the
operation.
– Arithmetic operators(+, -, *, /, %)
– Assignment operator(= , +=, -=, /=, *=, %=)
– Comparison operator(>, <, <=, >=, ==, !=)
• Binary operators can be overloaded as unary operator however binary operator
requires an additional parameter.
• In overloading binary operators the object to the left of the operator is used to
invoke the operator function while the operand to the right of the operator is
always passed as an argument to the function.
30By: Tekendra Nath Yogi
Arithmetic operators overloading
• Overloading plus operator:
– This operator adds the values of two operands when applied to a basic
data item.
– This operator can be overloaded to add the values of corresponding data
members when applied to two objects.
31By: Tekendra Nath Yogi
Contd..
32By: Tekendra Nath Yogi
Contd..
33By: Tekendra Nath Yogi
Contd..
• Note: in the same way we can overload other arithmetic
operators( -, *, /, %) to subtract, multiply, and divide objects.
34By: Tekendra Nath Yogi
Contd..
• Example: WAP to subtract one object from another object.
35By: Tekendra Nath Yogi
Contd..
36By: Tekendra Nath Yogi
Contd..
• Homework:
– Write a program to compute subtraction of two complex numbers using
operator overloading.
– Write a program to compute addition of two complex numbers using
operator overloading.
– WAP to multiply two objects.
– WAP to illustrate modulo and normal division of objects using operator
overloading.
37By: Tekendra Nath Yogi
Overloading comparison operator
• Comparison operator(>, <, <=, >=, ==, !=)
• Overloading comparison operator is almost similar to overloading arithmetic
operator except that it must return value of an integer type.
• This is because result of comparison is always true or false.
38By: Tekendra Nath Yogi
Contd..
• Overloading less than (<) operator:
39By: Tekendra Nath Yogi
Contd..
• Output:
40By: Tekendra Nath Yogi
Note: in the same way other
relational operators can be
overloaded.
Contd..
• Homework:
– Write a program that takes two amount (can be in RS and PS) as
input and decide which one is less.
– Write a program to compare the two distances taken as input in the
program and decide which one is greater than other.
41By: Tekendra Nath Yogi
Overloading assignment operator
• In c++ overloading of assignment(=) operator is possible.
• By overloading assignment operator, all values of one object can be
copied to another object by using assignment operator.
• Assignment operator must be overloaded by non-static member
function only.
• If the overloading function for the assignment operator is not written in
the class, the compiler generates the function to overload the
assignment operator.
42By: Tekendra Nath Yogi
Contd..
43By: Tekendra Nath Yogi
Contd..
44By: Tekendra Nath Yogi
Contd..
• Similar to copy constructor overriding:
– if the members of the objects are pointers then during assignment only the
address are copied. That is, both of the objects point to the same memory
area and they don not have distinct data.
• The difference is:
– copy constructor initializes during object creation where as the assignment
operator assigns(copies) to the already created(well constructed) object.
45By: Tekendra Nath Yogi
Data Conversion(Type conversion)
• It is the process of converting one type into another. In other words converting an
expression of a given type into another is called type conversion.
• A type conversion may either be explicit or implicit, depending on whether it is
ordered by the programmer or by the compiler.
• Explicit type conversions are used when a programmer want to get around the
compiler’s typing system.
• If the data types are user defined, the compiler does not support automatic type
conversion and therefore, we must design the conversion routine by ourselves.
46By: Tekendra Nath Yogi
Contd..
• Four types of situations might arise in the data conversion:
– Basic to basic
– Basic to user-defined
– User-defined to basic
– User-defined to user-defined
47By: Tekendra Nath Yogi
Contd..
• Conversion from basic type to user defined type:
– To convert basic types to user defined type(object) it is necessary to use
the constructor.
– The constructor in this case takes single argument whose type is to be
converted.
– Syntax:
48By: Tekendra Nath Yogi
Contd..
49By: Tekendra Nath Yogi
Contd..
Output:
50By: Tekendra Nath Yogi
Contd..
• Conversion from user defined type to basic type:
– To convert user defined types(objects) to basic type it is necessary to
overload cast operator.
– The overloaded cast operator does not have return type. Its implicit return
type is the type to which object need to be converted.
– To convert object to basic type, we use conversion function as below:
– Syntax:
51By: Tekendra Nath Yogi
Contd..
52By: Tekendra Nath Yogi
Contd..
• Output:
53By: Tekendra Nath Yogi
Contd..
• Conversion from user defined type to another user defined type:
– C++ compiler does not support data conversion between objects of user-
defined classes.
– This type of conversion can be carried out either by:
• A One argument constructor or
• an operator function.
– The choice between these two methods for data conversion depends on
whether the conversion function be defined in the source class or
destination class.
54By: Tekendra Nath Yogi
Contd..
• Consider the example:
Class A objA;
ClassB objB;
//…………
objA= ObjB;
– Conversion function can be defined in classA(destination) or classB(source).
– If the conversion function is to be defined in classA, one argument
constructor is used or
– if the conversion function is to be defined in source the conversion operator
function should be used.
55By: Tekendra Nath Yogi
Contd..
• Routine in source class: The syntax of conversion from user-
defined to user –defined when conversion is specified in the
source class:
56By: Tekendra Nath Yogi
Contd..
57By: Tekendra Nath Yogi
Contd..
58By: Tekendra Nath Yogi
Contd..
• Output:
59By: Tekendra Nath Yogi
Contd..
• Routine in destination class:
– In this case, it is necessary that the constructor be placed in the destination
class.
– This constructor is a single argument constructor and serves as instruction
for converting the argument’s type to the class type of which it is a
member.
60By: Tekendra Nath Yogi
Contd..
• Following is the syntax of conversion when conversion function
is in destination class:
61By: Tekendra Nath Yogi
Contd..
62By: Tekendra Nath Yogi
Contd..
63By: Tekendra Nath Yogi
Contd..
64By: Tekendra Nath Yogi
Homework
• What is operator overloading? What are the benefits of operator overloading
in C++? How is operator overloading different from function overloading.
• Which operators are not allowed to be overloaded? Why?
• What are the differences between overloading a unary operator and that of a
binary operator? Illustrate with suitable examples.
• What is difference between overloading a unary operator and that of a binary
operator? Illustrate with suitable examples.
• Write a program to convert polar co-ordinate into rectangular coordinate
using conversion/cast function.
65By: Tekendra Nath Yogi
Contd..
• Design a class Matrix of dimension 3x3. overload + operator to find sum of two materics.
• Write a program that decreases an integer value by 1 by overloading – - operator.
• Write a program that increases an integer value by 1 by overloading ++ operator.
• Write a program to find next element of Fibonacci series by overloading ++ operator.
• Why data conversion is needed? Write a program to convert kilogram into gram using user defined to
user defined data conversion.(1kg = 100gm).
• Write a program to convert an object of dollar class to object of rupees class. Assume that dollar class
has data members dol and cent an rupees class have data members rs and paisa.
• Write a program to convert object from class that represents temperature in Celsius scale to object of a
class that represents it in Fahrenheit scale.
• Write a program to convert object from a class that represents weight of gold in Nepal tola, to object of
a class that represents international gold measurement of weight in gram scale( 1 tola = 11.664 gram)
66By: Tekendra Nath Yogi
Thank You !
67By: Tekendra Nath Yogi

More Related Content

PPTX
B.sc CSIT 2nd semester C++ Unit6
PPTX
B.sc CSIT 2nd semester C++ Unit3
PPTX
B.sc CSIT 2nd semester C++ Unit5
PPTX
B.sc CSIT 2nd semester C++ Unit2
PPTX
Asymptotic notation
PDF
UGC NET Computer Science & Application book.pdf [Sample]
PPTX
3D Transformation
PPTX
B. SC CSIT Computer Graphics Unit 2 By Tekendra Nath Yogi
B.sc CSIT 2nd semester C++ Unit6
B.sc CSIT 2nd semester C++ Unit3
B.sc CSIT 2nd semester C++ Unit5
B.sc CSIT 2nd semester C++ Unit2
Asymptotic notation
UGC NET Computer Science & Application book.pdf [Sample]
3D Transformation
B. SC CSIT Computer Graphics Unit 2 By Tekendra Nath Yogi

What's hot (20)

PPTX
Basic Blocks and Flow Graphs
PPTX
3 D transformation translation, scaling
PPTX
Basics of calculus
PDF
Functions in discrete mathematics
PPTX
B. SC CSIT Computer Graphics Lab By Tekendra Nath Yogi
PDF
The Transformer in Vision | Xavier Giro | Master in Computer Vision Barcelona...
PPTX
3D transformation in computer graphics
PPTX
Syntax-Directed Translation into Three Address Code
PPT
PPT of Improper Integrals IMPROPER INTEGRAL
PPT
2D transformation (Computer Graphics)
PPT
Fill area algorithms
PDF
Point Collocation Method used in the solving of Differential Equations, parti...
PPTX
Diffusion models beat gans on image synthesis
PDF
[Paper review] contrastive language image pre-training, open ai, 2020
PDF
GAN - Generative Adversarial Nets
PPTX
2D Transformation
DOCX
Reflection, Scaling, Shear, Translation, and Rotation
PPTX
Understanding Black Box Models with Shapley Values
PPTX
Disjoint sets union, find
PPTX
3D Transformation in Computer Graphics
Basic Blocks and Flow Graphs
3 D transformation translation, scaling
Basics of calculus
Functions in discrete mathematics
B. SC CSIT Computer Graphics Lab By Tekendra Nath Yogi
The Transformer in Vision | Xavier Giro | Master in Computer Vision Barcelona...
3D transformation in computer graphics
Syntax-Directed Translation into Three Address Code
PPT of Improper Integrals IMPROPER INTEGRAL
2D transformation (Computer Graphics)
Fill area algorithms
Point Collocation Method used in the solving of Differential Equations, parti...
Diffusion models beat gans on image synthesis
[Paper review] contrastive language image pre-training, open ai, 2020
GAN - Generative Adversarial Nets
2D Transformation
Reflection, Scaling, Shear, Translation, and Rotation
Understanding Black Box Models with Shapley Values
Disjoint sets union, find
3D Transformation in Computer Graphics
Ad

Similar to B.sc CSIT 2nd semester C++ Unit4 (20)

PPT
C++ - Constructors,Destructors, Operator overloading and Type conversion
PDF
OOPS-Seminar.pdf
PDF
Oop05 6
PPTX
2CPP13 - Operator Overloading
PPTX
Cpp (C++)
PPTX
Operator overloadng
PPT
9781285852744 ppt ch13
PDF
OOP_UnitIII.pdf
PDF
Lec 8.pdf a
PPTX
OPERATOR OVERLOADING IN C++
PPT
3d7b7 session4 c++
PPTX
Operator in c programming
PDF
NIKUL SURANI
PPTX
Operator Overloading
PPTX
Intro To C++ - Class #19: Functions
PPTX
Presentation on overloading
PPTX
Operator overloaing
PPTX
PPTX
Operator overloading
C++ - Constructors,Destructors, Operator overloading and Type conversion
OOPS-Seminar.pdf
Oop05 6
2CPP13 - Operator Overloading
Cpp (C++)
Operator overloadng
9781285852744 ppt ch13
OOP_UnitIII.pdf
Lec 8.pdf a
OPERATOR OVERLOADING IN C++
3d7b7 session4 c++
Operator in c programming
NIKUL SURANI
Operator Overloading
Intro To C++ - Class #19: Functions
Presentation on overloading
Operator overloaing
Operator overloading
Ad

More from Tekendra Nath Yogi (20)

PDF
Unit9:Expert System
PDF
Unit7: Production System
PDF
Unit8: Uncertainty in AI
PDF
Unit5: Learning
PDF
Unit4: Knowledge Representation
PDF
Unit3:Informed and Uninformed search
PDF
Unit2: Agents and Environment
PDF
Unit1: Introduction to AI
PDF
Unit 6: Application of AI
PPTX
PDF
BIM Data Mining Unit5 by Tekendra Nath Yogi
PDF
BIM Data Mining Unit4 by Tekendra Nath Yogi
PDF
BIM Data Mining Unit3 by Tekendra Nath Yogi
PDF
BIM Data Mining Unit2 by Tekendra Nath Yogi
PDF
BIM Data Mining Unit1 by Tekendra Nath Yogi
PPTX
B. SC CSIT Computer Graphics Unit 5 By Tekendra Nath Yogi
Unit9:Expert System
Unit7: Production System
Unit8: Uncertainty in AI
Unit5: Learning
Unit4: Knowledge Representation
Unit3:Informed and Uninformed search
Unit2: Agents and Environment
Unit1: Introduction to AI
Unit 6: Application of AI
BIM Data Mining Unit5 by Tekendra Nath Yogi
BIM Data Mining Unit4 by Tekendra Nath Yogi
BIM Data Mining Unit3 by Tekendra Nath Yogi
BIM Data Mining Unit2 by Tekendra Nath Yogi
BIM Data Mining Unit1 by Tekendra Nath Yogi
B. SC CSIT Computer Graphics Unit 5 By Tekendra Nath Yogi

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
Updated Idioms and Phrasal Verbs in English subject
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Types and Its function , kingdom of life
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Computing-Curriculum for Schools in Ghana
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
master seminar digital applications in india
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Supply Chain Operations Speaking Notes -ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Structure & Organelles in detailed.
Paper A Mock Exam 9_ Attempt review.pdf.
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Updated Idioms and Phrasal Verbs in English subject
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
01-Introduction-to-Information-Management.pdf
Microbial diseases, their pathogenesis and prophylaxis
A systematic review of self-coping strategies used by university students to ...
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Microbial disease of the cardiovascular and lymphatic systems
Cell Types and Its function , kingdom of life
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Computing-Curriculum for Schools in Ghana
Practical Manual AGRO-233 Principles and Practices of Natural Farming
master seminar digital applications in india
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...

B.sc CSIT 2nd semester C++ Unit4

  • 1. Unit4 Operator overloading Presented By : Tekendra Nath Yogi [email protected] College Of Applied Business And Technology
  • 2. Introduction • C++ provides a rich collection of operators(e.g., +, -, /, *….etc). Such operators are used with the fundamental types(int, float, char,…..etc). – E.g., int a, b, c; a= b+c is perfectly valid • But if we try to use these operators directly with user defined types (e.g., objects) compiler will produce error. – E.g., if a, b, c are objects of user defined class then the statement a = b+c is not valid • So to use operators with objects we need to overload operators (i.e., Customizes the C++ operators for operands of user-defined types.). – E,g, a= b+c can be made valid by using overloading. 2By: Tekendra Nath Yogi
  • 3. Contd.. • What is operator overloading? – The mechanism of giving special meanings to an operator is called operator overloading. – i.e., redefine the way operator behaves so that we can use them with user-defined types. – Although the semantics of an operator can be extended, we can not change its syntax and semantics that govern its use such as the number of operand, precedence and associativity. • E.g., For example, the operator + should be overloaded for addition, not subtraction. 3By: Tekendra Nath Yogi
  • 4. Contd.. • Syntax: – operator overloading is done with the help of special function, called the operator function. The general form of operator function is as follows: 4By: Tekendra Nath Yogi
  • 5. Contd.. • Example: – To add two objects of type distance each having a data members feet of type int and inches of type float, we can over load + operator as follows: 5By: Tekendra Nath Yogi
  • 6. General rules(Restrictions) for operator overloading • We can not invent new operators that do not exist in the language. • i.e., only existing operator in the language can be overloaded. – E.g., @ is not a valid c++ operator and can not be overloaded 6By: Tekendra Nath Yogi
  • 7. Contd.. • Overloaded operator must follow the same syntax: – E.g., if x and y are objects of a user defined class then • X++12; // not allowed: ++ is not a binary operator • X++; is allowed • %x ; is not allowed: % is not an unary operator • Y= x%3; is allowed • One can not change the number of operand used by the operator. • Try to overload operator where they make sense. 7By: Tekendra Nath Yogi
  • 8. Contd.. • We can not change the way an operator works between native c++ types. – E.g ., we can not change how works between a double and an integer variable. – But we can change the working of operator for user defined types. 8By: Tekendra Nath Yogi
  • 9. Contd.. • We can not change the operator precedence rules. • i.e., the order of operator evaluation remains unchanged. 9By: Tekendra Nath Yogi
  • 10. Contd.. • We can not change the operator associativity rules. – E.g., the unary minus(-) operator associates from right to left. x= -y; // unary minus associates from right to left x = y-; // we can not alter unary minus to go from left to right. 10By: Tekendra Nath Yogi
  • 11. Contd.. • Overloading some operators does not implicitly define other operators for us. – E.g., overloading the + and = operators for a class does not mean that the += operator is overloaded automatically for us. We will need to write overload code for the += operator as well. 11By: Tekendra Nath Yogi
  • 12. Contd.. • The overloaded operator must have at least one operand that is of user-defined type. • When overloading an operator using a member function: • The leftmost operand of the overloaded operator must be an object of the class type. • The leftmost operand becomes the implicit parameter. All other operands become function parameter. 12By: Tekendra Nath Yogi
  • 13. Contd.. • Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded. Operator that are not overloaded are follows – scope operator (::) – sizeof – member selector –(.) – member pointer selector (.*) – ternary operator (?:) 13By: Tekendra Nath Yogi
  • 14. Overloading Unary operator • The operators which acts upon only one operand are called unary operators. • The following is a list of unary operator that can be overloaded in c++: – Unary minus(-) – Unary plus(+) – Ones complement(~) – Pointer dereference(*) – Not (!) – Increment operator(++) – Decrement operator(--) 14By: Tekendra Nath Yogi
  • 15. Contd.. • Prefix(++, --) and postfix (++. --)unary operator overloading: – Increment operators increase the value of operand by 1, while decrement operators(--) decrease value of operand by 1. – They can be written either before the operand or after it. Depending on its location, they can be classified as either prefix operators or postfix operators. – If the increment and decrement operators are written before the operand, then they are termed as prefix operators. However, if they are written after the operand, then they are termed as postfix operators. 15By: Tekendra Nath Yogi
  • 17. Contd.. • Overloading prefix increment operator: 17By: Tekendra Nath Yogi
  • 19. Contd.. • Overloading prefix decrement operator: 19By: Tekendra Nath Yogi
  • 21. Contd.. • Class work: WAP to overload prefix operator as shown above use parameterized constructor to initialize the value of data member count. 21By: Tekendra Nath Yogi
  • 22. Contd.. • Overload postfix increment operator: 22By: Tekendra Nath Yogi
  • 24. Contd..• Overload postfix decrement operator: 24By: Tekendra Nath Yogi
  • 26. • Returning values from operator function: Returning values using temporary objects: 26By: Tekendra Nath Yogi
  • 28. Contd.. • Returning values using nameless temporary objects: 28By: Tekendra Nath Yogi
  • 30. Overloading Binary Operators • Binary operator are operators, which require two operands to perform the operation. – Arithmetic operators(+, -, *, /, %) – Assignment operator(= , +=, -=, /=, *=, %=) – Comparison operator(>, <, <=, >=, ==, !=) • Binary operators can be overloaded as unary operator however binary operator requires an additional parameter. • In overloading binary operators the object to the left of the operator is used to invoke the operator function while the operand to the right of the operator is always passed as an argument to the function. 30By: Tekendra Nath Yogi
  • 31. Arithmetic operators overloading • Overloading plus operator: – This operator adds the values of two operands when applied to a basic data item. – This operator can be overloaded to add the values of corresponding data members when applied to two objects. 31By: Tekendra Nath Yogi
  • 34. Contd.. • Note: in the same way we can overload other arithmetic operators( -, *, /, %) to subtract, multiply, and divide objects. 34By: Tekendra Nath Yogi
  • 35. Contd.. • Example: WAP to subtract one object from another object. 35By: Tekendra Nath Yogi
  • 37. Contd.. • Homework: – Write a program to compute subtraction of two complex numbers using operator overloading. – Write a program to compute addition of two complex numbers using operator overloading. – WAP to multiply two objects. – WAP to illustrate modulo and normal division of objects using operator overloading. 37By: Tekendra Nath Yogi
  • 38. Overloading comparison operator • Comparison operator(>, <, <=, >=, ==, !=) • Overloading comparison operator is almost similar to overloading arithmetic operator except that it must return value of an integer type. • This is because result of comparison is always true or false. 38By: Tekendra Nath Yogi
  • 39. Contd.. • Overloading less than (<) operator: 39By: Tekendra Nath Yogi
  • 40. Contd.. • Output: 40By: Tekendra Nath Yogi Note: in the same way other relational operators can be overloaded.
  • 41. Contd.. • Homework: – Write a program that takes two amount (can be in RS and PS) as input and decide which one is less. – Write a program to compare the two distances taken as input in the program and decide which one is greater than other. 41By: Tekendra Nath Yogi
  • 42. Overloading assignment operator • In c++ overloading of assignment(=) operator is possible. • By overloading assignment operator, all values of one object can be copied to another object by using assignment operator. • Assignment operator must be overloaded by non-static member function only. • If the overloading function for the assignment operator is not written in the class, the compiler generates the function to overload the assignment operator. 42By: Tekendra Nath Yogi
  • 45. Contd.. • Similar to copy constructor overriding: – if the members of the objects are pointers then during assignment only the address are copied. That is, both of the objects point to the same memory area and they don not have distinct data. • The difference is: – copy constructor initializes during object creation where as the assignment operator assigns(copies) to the already created(well constructed) object. 45By: Tekendra Nath Yogi
  • 46. Data Conversion(Type conversion) • It is the process of converting one type into another. In other words converting an expression of a given type into another is called type conversion. • A type conversion may either be explicit or implicit, depending on whether it is ordered by the programmer or by the compiler. • Explicit type conversions are used when a programmer want to get around the compiler’s typing system. • If the data types are user defined, the compiler does not support automatic type conversion and therefore, we must design the conversion routine by ourselves. 46By: Tekendra Nath Yogi
  • 47. Contd.. • Four types of situations might arise in the data conversion: – Basic to basic – Basic to user-defined – User-defined to basic – User-defined to user-defined 47By: Tekendra Nath Yogi
  • 48. Contd.. • Conversion from basic type to user defined type: – To convert basic types to user defined type(object) it is necessary to use the constructor. – The constructor in this case takes single argument whose type is to be converted. – Syntax: 48By: Tekendra Nath Yogi
  • 51. Contd.. • Conversion from user defined type to basic type: – To convert user defined types(objects) to basic type it is necessary to overload cast operator. – The overloaded cast operator does not have return type. Its implicit return type is the type to which object need to be converted. – To convert object to basic type, we use conversion function as below: – Syntax: 51By: Tekendra Nath Yogi
  • 54. Contd.. • Conversion from user defined type to another user defined type: – C++ compiler does not support data conversion between objects of user- defined classes. – This type of conversion can be carried out either by: • A One argument constructor or • an operator function. – The choice between these two methods for data conversion depends on whether the conversion function be defined in the source class or destination class. 54By: Tekendra Nath Yogi
  • 55. Contd.. • Consider the example: Class A objA; ClassB objB; //………… objA= ObjB; – Conversion function can be defined in classA(destination) or classB(source). – If the conversion function is to be defined in classA, one argument constructor is used or – if the conversion function is to be defined in source the conversion operator function should be used. 55By: Tekendra Nath Yogi
  • 56. Contd.. • Routine in source class: The syntax of conversion from user- defined to user –defined when conversion is specified in the source class: 56By: Tekendra Nath Yogi
  • 60. Contd.. • Routine in destination class: – In this case, it is necessary that the constructor be placed in the destination class. – This constructor is a single argument constructor and serves as instruction for converting the argument’s type to the class type of which it is a member. 60By: Tekendra Nath Yogi
  • 61. Contd.. • Following is the syntax of conversion when conversion function is in destination class: 61By: Tekendra Nath Yogi
  • 65. Homework • What is operator overloading? What are the benefits of operator overloading in C++? How is operator overloading different from function overloading. • Which operators are not allowed to be overloaded? Why? • What are the differences between overloading a unary operator and that of a binary operator? Illustrate with suitable examples. • What is difference between overloading a unary operator and that of a binary operator? Illustrate with suitable examples. • Write a program to convert polar co-ordinate into rectangular coordinate using conversion/cast function. 65By: Tekendra Nath Yogi
  • 66. Contd.. • Design a class Matrix of dimension 3x3. overload + operator to find sum of two materics. • Write a program that decreases an integer value by 1 by overloading – - operator. • Write a program that increases an integer value by 1 by overloading ++ operator. • Write a program to find next element of Fibonacci series by overloading ++ operator. • Why data conversion is needed? Write a program to convert kilogram into gram using user defined to user defined data conversion.(1kg = 100gm). • Write a program to convert an object of dollar class to object of rupees class. Assume that dollar class has data members dol and cent an rupees class have data members rs and paisa. • Write a program to convert object from class that represents temperature in Celsius scale to object of a class that represents it in Fahrenheit scale. • Write a program to convert object from a class that represents weight of gold in Nepal tola, to object of a class that represents international gold measurement of weight in gram scale( 1 tola = 11.664 gram) 66By: Tekendra Nath Yogi
  • 67. Thank You ! 67By: Tekendra Nath Yogi