SlideShare a Scribd company logo
1 of 51
Download to read offline
Mrs. Pranali P. Chaudhari
Operator Overloading
Contents
 Operator Overloading
 Overloading Unary and Binary Operator
 Overloading using friend function
 Type casting andType conversion
Quiz 1
 What is Operator Overloading?
 Operator overloading is a specific case of
polymorphism in which some or all operators like +,
= or == are treated as polymorphic functions and as
such have different behaviours depending on the types
of its arguments.
Operator Overloading
 Operator overloading is a specific case of polymorphism in which
some or all of operators like +, =, or == have different
implementations depending on the types of their arguments.
 Operator overloading gives us the opportunity to redefine the
C++ language.
 C++ permits us to add two variables of user defined types with
the same syntax that is applied to the basic data types.
Restrictions on Operator Overloading
 Overloading restrictions
 Precedence of an operator cannot be changed
 Associatively 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
Restrictions on Operator Overloading
 Following operators can’t be overloaded:
 Class member access operators (., .*)
 Scope resolution operator (::)
 Size operator (sizeof )
 Conditional operator (?:)
 All other operators can be overload
Defining Operator Overloading
 General syntax for operator overloading is:
return type classname :: operator op(arglist)
{
Function body
}
For e.g.:
vector operator +(vector);
 vector is a data type of class.
Operator Overloading Process
 The process of overloading involves the following steps:
 Create a class that defines the data type that is to be used in the
overloading operation.
 Declare the operator function operator op() in the public part
of the class.
 Define the operator function to implement the required
operations.
Overloading Unary Operators
 Consider unary minus operator (changes the sign of the
operand)
 The unary minus when applied to an object should change
the sign of each of its data items.
Overloading Unary Operators
class space
{
int x, y, z;
public:
void getdata( int a, int b, int c);
void display(void);
void operator - (); // overload unary minus operator
};
Overloading Unary Operators
void space :: getdata(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void space :: display(void)
{
cout << x ;
cout << y ;
cout << z ;
}
Overloading Unary Operators
void space :: operator - ()
{
x = -x;
y = -y;
z = -z;
}
int main()
{
space S;
S.getdata(10, 20, 30);
S.display();
-S; // activates operator-() function
S.display();
return 0;
}
Practice Statement 1
 Create a class date with day, month and year as its
members. Accept the date from the user and display it.
Overload the increment and decrement operators for
displaying the next and previous date for the given date.
Overloading Binary Operators
 As a unary operator is overloaded we can also overload a binary
operator.
 For e.g: A binary operator + can be overloaded to add two objects
rather than adding two variables.
 Using operator overloading a functional notation,
C = sum(A, B);
Can be replaced by,
C = A + B;
Overloading Binary Operators
class complex
{
float x;
float y;
public:
complex(){}
complex(float real, float imag)
{
x = real;
y = imag;
}
complex operator + (complex);
void display(void);
};
Overloading Binary Operators
complex complex :: operator + (complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return (temp);
}
void complex :: display(void)
{
cout << x << “ + j “ << y ;
}
Overloading Binary Operators
int main()
{
complex C1, C2, C3;
C1 = complex(2.5, 3.5);
C2 = complex(1.6, 2.7);
C3 = C1 + C2; // invokes operator+() function
cout << “ C1 = “; C1.display();
cout << “ C2 = “; C2.display();
cout << “ C3 = “; C3.display();
return 0;
}
Overloading binary operators using
Friends
 Friend functions may be used in place of member functions
for overloading a binary operator.
 A friend function requires two arguments to be explicitly
passed to it, while a member function requires only one.
 For e.g:
complex operator + (complex);
friend complex operator + (complex, complex);
Overloading binary operators using
Friends
 The operator function definition would also be modified as:
complex complex :: operator+(complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return(temp);
}
complex operator + (complex a, complex b)
{
return complex((a.x + b.x), (a.y + b.y));
}
Overloading binary operators using
Friends
 The statement,
C3 = C1 + C2;
Is equivalent to
C3 = operator+(C1, C2);
String Manipulations using friends
class string
{
char *p;
int len;
public:
string() { len = 0; p = 0;}
string( const char * s );
string ( const string & s );
~ string () { delete p; }
friend string operator+(const string & s , const string & t );
friend int operator<=(const string & s, const string & t );
friend void show( const string s);
};
String Manipulations using friends
string :: string ( const char * s)
{
len = strlen(s);
p = new char[len + 1];
strcpy(p, s);
}
string :: string (const string & s)
{
len = s. len;
p = new char[len+1];
strcpy(p, s.p);
}
String Manipulations using friends
String operator+(const string &s, const string &t)
{
string temp;
temp.len = s.len + t.len;
temp.p = new char[temp.len+1];
strcpy(temp.p, s.p);
strcat(temp.p, t.p);
return(temp);
}
String Manipulations using friends
int operator<=(const string &s , const string &t)
{
int m = strlen(s.p);
int n = strlen(t.p);
if( m <= n) return(1);
else return (0);
}
void show (const string s)
{
cout << s.p;
}
String Manipulations using friends
int main()
{
string s1 = “New”;
string s2 = “York”;
string s3 = “Delhi”;
string t1, t2, t3;
t1 = s1;
t2 = s2;
t3 = s1 + s3;
show(t1); show(t2); show(t3);
String Manipulations using friends
if ( t1 <= t3)
{
show(t1);
cout << “smaller than”;
show(t3);
}
else
{
show(t3);
cout << “smaller than”;
show(t1);
}
return 0;
}
Overloading Stream Insertion and
Extraction Operators
 It is possible to overload the stream insertion (<<) and
extraction operators (>>) to work with classes.
 This has advantages, in that
 It makes programs more readable
 It makes programs more extensible
 It makes input and output more consistent
Overloading Stream Insertion and
Extraction Operators
istream & operator >> (istream &din, vector &b)
{
for (int i = 0; i < size; i++)
{
din>>b.v[i];
}
return(din);
}
Overloading Stream Insertion and
Extraction Operators
ostream & operator << (ostream &dout, rational &b)
{
dout<<“(“;
for (int i = 0; i < size; i++)
{
din>>b.v[i];
}
dout << “)”;
return(dout);
}
Practice Statement 2
 Create a class rational to accept a rational number.
Perform all the arithmetic operations on rational
numbers by overloading all arithmetic operators ( +, - ,
* , / ). Also overload >> and << operators for taking
rational numbers as input and display them.
Type Conversion
 Type conversion is a process of converting one data type to
another.
 Type conversion is done automatically for the built-in
datatypes by the compiler.
 Example:
int m;
float x = 3.14159;
m = x;
 The above statements convert x to an integer before
assigning it to m.
 For user defined data type the compiler has to be provided
with the type conversion function.
Type Conversion
 There are three situations that arise when performing data
type conversion between incompatible types:
 Conversion from basic type to class type
 Conversion from class type to basic type
 Conversion from one class type to another class type
Basic type to Class type
 The conversion from basic type to class type is easily accomplish
by the use of constructors.
 Constructors are used to initialize the objects and we can use
them to build a class type object from an basic type.
 For example we can create a vector object from an int type array.
 The constructors perform a defacto type conversion from the
argument’s type to the constructor’s class type.
 The constructors used for the type conversion take a single
argument whose type is to be converted.
Basic type to class type (Example)
class time
{
int hrs;
int mins;
public:
time (int t) // constructor
{
hrs = t/60; // t in minutes
mins = t%60;
}
};
The following conversion statements can be used in a function:
time t1; // object t1 created
int duration = 85;
t1 = duration; // int to class type
Class type to Basic type
 C++ allows an overloaded casting operator that could be
used to convert a class type data to a basic type.
 General syntax:
Operator typename()
{
...........
...........
}
This function converts a class type data to typename.
 For example, the operator double() converts a class
object to type double.
Class type to Basic type (Example)
Vector :: operator double()
{
double sum = 0;
for(int i =0; i<size; i++)
{
sum = sum + v[i] * v[i];
return sqrt(sum);
}
}
 This function converts a vector to the corresponding scalar
magnitude.
 The operator double() can be used as
double length = double(v1); OR
double length = v1;
Class type to Basic type
 The casting operator function should satisfy the following
conditions:
 It must be a class member.
 It must not specify a return type.
 It must not have any arguments.
One class to Another class type
 Conversions between objects of different classes can be
carried out by either a constructor or a conversion function.
 Consider the statement:
objX = objY;
 The class Y type data is converted to the class X type data and
the converted value is assigned to the objX.
 The class Y is known as source class and class X is known
as destination class.
One class to Another class type
 When to use constructor and type conversion function?
One class to Another class type
(Example)
 Consider an example of an inventory of products in store.
 One way of recording the details of the product is to record
their code number, total items in the stock and the cost of
each item.
 Another approach is to just specify the item code and the
value of the item in the stock.
 Example.
Type conversion summary
Summary
 State whetherTrue or False:
 Using the operator overloading concept, we can change the
meaning of an operator.
 Friend functions cannot be used to overload operators.
 When using an overloaded binary operator, the left operand is
implicitly passed to the member function.
 The overloaded operator must have atleast one operand that is
user-defined type.
 Operator functions never return a value.
 Through operator overloading, a class type data can be converted
to a basic type.
 A constructor can be used to convert a basic type to a class type
data.
Short Answer Questions
 Why is it necessary to overload and operator?
 Operator overloading allows us to provide new implementations
for existing operators. Using operator overloading one can perform
the operation on the user defined data types in the same way as that
of built-in data types.
 Example: Two integer values can be added as c = a + b. With the
use of operator overloading the + operator can also be used to
perform addition of two complex numbers as:
C3 = C1 + C2 where C1, C2 and C3 are the objects of class
complex.
Short Answer Questions
 When is a friend function compulsory? Give example.
 Friend function is used in a situation where we need to use two
different types of operands for a binary operator. One an object and
another a built-in data type.
A = 2 + B
 Here the statement will not be executed by the member functions
as the left hand operand which is responsible for invoking the
member function is not the object of the same class. However the
friend function allows the statement to be executed.
Short Answer Questions
 A friend function cannot be used to overload the
assignment operator = . Explain why?
 In the assignment operator, the right hand operand is source and
lefthand operand is the target of assignment. When we overload
assignment operator as member function then the Lvalue becomes
the object for which the assignment operator is called and the Rvalue
object is passed as parameter. If the Rvalue is constant then by using
the constructor that value can be converted into object and then will
be passed as parameter to the assignment operator. But in case of
friend function both the Lvalue and Rvalue needs to be passed as
parameter. If the Lvalue is constant then it gets converted into the
class object by constructor which results in changing the constant
value which is not allowed/illegal. Hence, to avoid modifying
constant as Lvalue assignment operator was restricted to be
overloaded as friend function.
Short Answer Questions
 Name the operators that cannot be overloaded.
 Class member access operators (., .*)
 Scope resolution operator (::)
 Size operator (sizeof )
 Conditional operator (?:)
 Name the operators that cannot be overloaded
using friend function.
 Assignment operator ( = )
 Function call operator ( )
 Subscripting operator [ ]
 Class member access operator ( -> )
Short Answer Questions
 What is conversion function. How is it created.
Explain its syntax.
 The conversion function is the overloaded casting operator
that is used to convert a class type data to basic type data.
 Syntax:
Operator typename()
{
...........
...........
}
 This function converts a class type data to typename.
 Operator int() converts a class type object to type int.
Short Answer Questions
 A class alpha has a constructor as follows:
Alpha ( int a, double b);
Can we use this constructor to convert types?
 No, we cannot use this constructor to convert types because
when the constructors are used for the type conversion it take a
single argument whose type is to be converted.
 In the given example the alpha constructor is having two
arguments int and double.
Short Answer Questions
 We have two classes X and Y. If a is an object of X
and b is an object of Y and we want to say a = b;
what type of conversion routine should be used and
where?
 To perform the conversion a = b we use the type casting
operator function in the source class. The conversion takes place
in theY class and the result is given to the X class.
References
 Object Oriented Programming with C++ by E.
Balagurusamy.
End of unit

More Related Content

What's hot (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Functions in C
Functions in CFunctions in C
Functions in C
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Structure in C
Structure in CStructure in C
Structure in C
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Interface
InterfaceInterface
Interface
 
Function overloading
Function overloadingFunction overloading
Function overloading
 

Similar to Operator overloading

overloading in C++
overloading in C++overloading in C++
overloading in C++Prof Ansari
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Yaksh Jethva
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfesuEthopi
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpprajshreemuthiah
 
operator overloading
operator overloadingoperator overloading
operator overloadingNishant Joshi
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 

Similar to Operator overloading (20)

overloading in C++
overloading in C++overloading in C++
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 overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
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
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Lecture5
Lecture5Lecture5
Lecture5
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Array Cont
Array ContArray Cont
Array Cont
 
Bc0037
Bc0037Bc0037
Bc0037
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
CppOperators.ppt
CppOperators.pptCppOperators.ppt
CppOperators.ppt
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 

More from Pranali Chaudhari (8)

Exception handling
Exception handlingException handling
Exception handling
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Templates
TemplatesTemplates
Templates
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 

Recently uploaded

Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 

Recently uploaded (20)

Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 

Operator overloading

  • 1. Mrs. Pranali P. Chaudhari Operator Overloading
  • 2. Contents  Operator Overloading  Overloading Unary and Binary Operator  Overloading using friend function  Type casting andType conversion
  • 3. Quiz 1  What is Operator Overloading?  Operator overloading is a specific case of polymorphism in which some or all operators like +, = or == are treated as polymorphic functions and as such have different behaviours depending on the types of its arguments.
  • 4. Operator Overloading  Operator overloading is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments.  Operator overloading gives us the opportunity to redefine the C++ language.  C++ permits us to add two variables of user defined types with the same syntax that is applied to the basic data types.
  • 5. Restrictions on Operator Overloading  Overloading restrictions  Precedence of an operator cannot be changed  Associatively 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
  • 6. Restrictions on Operator Overloading  Following operators can’t be overloaded:  Class member access operators (., .*)  Scope resolution operator (::)  Size operator (sizeof )  Conditional operator (?:)  All other operators can be overload
  • 7. Defining Operator Overloading  General syntax for operator overloading is: return type classname :: operator op(arglist) { Function body } For e.g.: vector operator +(vector);  vector is a data type of class.
  • 8. Operator Overloading Process  The process of overloading involves the following steps:  Create a class that defines the data type that is to be used in the overloading operation.  Declare the operator function operator op() in the public part of the class.  Define the operator function to implement the required operations.
  • 9. Overloading Unary Operators  Consider unary minus operator (changes the sign of the operand)  The unary minus when applied to an object should change the sign of each of its data items.
  • 10. Overloading Unary Operators class space { int x, y, z; public: void getdata( int a, int b, int c); void display(void); void operator - (); // overload unary minus operator };
  • 11. Overloading Unary Operators void space :: getdata(int a, int b, int c) { x = a; y = b; z = c; } void space :: display(void) { cout << x ; cout << y ; cout << z ; }
  • 12. Overloading Unary Operators void space :: operator - () { x = -x; y = -y; z = -z; } int main() { space S; S.getdata(10, 20, 30); S.display(); -S; // activates operator-() function S.display(); return 0; }
  • 13. Practice Statement 1  Create a class date with day, month and year as its members. Accept the date from the user and display it. Overload the increment and decrement operators for displaying the next and previous date for the given date.
  • 14. Overloading Binary Operators  As a unary operator is overloaded we can also overload a binary operator.  For e.g: A binary operator + can be overloaded to add two objects rather than adding two variables.  Using operator overloading a functional notation, C = sum(A, B); Can be replaced by, C = A + B;
  • 15. Overloading Binary Operators class complex { float x; float y; public: complex(){} complex(float real, float imag) { x = real; y = imag; } complex operator + (complex); void display(void); };
  • 16. Overloading Binary Operators complex complex :: operator + (complex c) { complex temp; temp.x = x + c.x; temp.y = y + c.y; return (temp); } void complex :: display(void) { cout << x << “ + j “ << y ; }
  • 17. Overloading Binary Operators int main() { complex C1, C2, C3; C1 = complex(2.5, 3.5); C2 = complex(1.6, 2.7); C3 = C1 + C2; // invokes operator+() function cout << “ C1 = “; C1.display(); cout << “ C2 = “; C2.display(); cout << “ C3 = “; C3.display(); return 0; }
  • 18. Overloading binary operators using Friends  Friend functions may be used in place of member functions for overloading a binary operator.  A friend function requires two arguments to be explicitly passed to it, while a member function requires only one.  For e.g: complex operator + (complex); friend complex operator + (complex, complex);
  • 19. Overloading binary operators using Friends  The operator function definition would also be modified as: complex complex :: operator+(complex c) { complex temp; temp.x = x + c.x; temp.y = y + c.y; return(temp); } complex operator + (complex a, complex b) { return complex((a.x + b.x), (a.y + b.y)); }
  • 20. Overloading binary operators using Friends  The statement, C3 = C1 + C2; Is equivalent to C3 = operator+(C1, C2);
  • 21. String Manipulations using friends class string { char *p; int len; public: string() { len = 0; p = 0;} string( const char * s ); string ( const string & s ); ~ string () { delete p; } friend string operator+(const string & s , const string & t ); friend int operator<=(const string & s, const string & t ); friend void show( const string s); };
  • 22. String Manipulations using friends string :: string ( const char * s) { len = strlen(s); p = new char[len + 1]; strcpy(p, s); } string :: string (const string & s) { len = s. len; p = new char[len+1]; strcpy(p, s.p); }
  • 23. String Manipulations using friends String operator+(const string &s, const string &t) { string temp; temp.len = s.len + t.len; temp.p = new char[temp.len+1]; strcpy(temp.p, s.p); strcat(temp.p, t.p); return(temp); }
  • 24. String Manipulations using friends int operator<=(const string &s , const string &t) { int m = strlen(s.p); int n = strlen(t.p); if( m <= n) return(1); else return (0); } void show (const string s) { cout << s.p; }
  • 25. String Manipulations using friends int main() { string s1 = “New”; string s2 = “York”; string s3 = “Delhi”; string t1, t2, t3; t1 = s1; t2 = s2; t3 = s1 + s3; show(t1); show(t2); show(t3);
  • 26. String Manipulations using friends if ( t1 <= t3) { show(t1); cout << “smaller than”; show(t3); } else { show(t3); cout << “smaller than”; show(t1); } return 0; }
  • 27. Overloading Stream Insertion and Extraction Operators  It is possible to overload the stream insertion (<<) and extraction operators (>>) to work with classes.  This has advantages, in that  It makes programs more readable  It makes programs more extensible  It makes input and output more consistent
  • 28. Overloading Stream Insertion and Extraction Operators istream & operator >> (istream &din, vector &b) { for (int i = 0; i < size; i++) { din>>b.v[i]; } return(din); }
  • 29. Overloading Stream Insertion and Extraction Operators ostream & operator << (ostream &dout, rational &b) { dout<<“(“; for (int i = 0; i < size; i++) { din>>b.v[i]; } dout << “)”; return(dout); }
  • 30. Practice Statement 2  Create a class rational to accept a rational number. Perform all the arithmetic operations on rational numbers by overloading all arithmetic operators ( +, - , * , / ). Also overload >> and << operators for taking rational numbers as input and display them.
  • 31. Type Conversion  Type conversion is a process of converting one data type to another.  Type conversion is done automatically for the built-in datatypes by the compiler.  Example: int m; float x = 3.14159; m = x;  The above statements convert x to an integer before assigning it to m.  For user defined data type the compiler has to be provided with the type conversion function.
  • 32. Type Conversion  There are three situations that arise when performing data type conversion between incompatible types:  Conversion from basic type to class type  Conversion from class type to basic type  Conversion from one class type to another class type
  • 33. Basic type to Class type  The conversion from basic type to class type is easily accomplish by the use of constructors.  Constructors are used to initialize the objects and we can use them to build a class type object from an basic type.  For example we can create a vector object from an int type array.  The constructors perform a defacto type conversion from the argument’s type to the constructor’s class type.  The constructors used for the type conversion take a single argument whose type is to be converted.
  • 34. Basic type to class type (Example) class time { int hrs; int mins; public: time (int t) // constructor { hrs = t/60; // t in minutes mins = t%60; } }; The following conversion statements can be used in a function: time t1; // object t1 created int duration = 85; t1 = duration; // int to class type
  • 35. Class type to Basic type  C++ allows an overloaded casting operator that could be used to convert a class type data to a basic type.  General syntax: Operator typename() { ........... ........... } This function converts a class type data to typename.  For example, the operator double() converts a class object to type double.
  • 36. Class type to Basic type (Example) Vector :: operator double() { double sum = 0; for(int i =0; i<size; i++) { sum = sum + v[i] * v[i]; return sqrt(sum); } }  This function converts a vector to the corresponding scalar magnitude.  The operator double() can be used as double length = double(v1); OR double length = v1;
  • 37. Class type to Basic type  The casting operator function should satisfy the following conditions:  It must be a class member.  It must not specify a return type.  It must not have any arguments.
  • 38. One class to Another class type  Conversions between objects of different classes can be carried out by either a constructor or a conversion function.  Consider the statement: objX = objY;  The class Y type data is converted to the class X type data and the converted value is assigned to the objX.  The class Y is known as source class and class X is known as destination class.
  • 39. One class to Another class type  When to use constructor and type conversion function?
  • 40. One class to Another class type (Example)  Consider an example of an inventory of products in store.  One way of recording the details of the product is to record their code number, total items in the stock and the cost of each item.  Another approach is to just specify the item code and the value of the item in the stock.  Example.
  • 42. Summary  State whetherTrue or False:  Using the operator overloading concept, we can change the meaning of an operator.  Friend functions cannot be used to overload operators.  When using an overloaded binary operator, the left operand is implicitly passed to the member function.  The overloaded operator must have atleast one operand that is user-defined type.  Operator functions never return a value.  Through operator overloading, a class type data can be converted to a basic type.  A constructor can be used to convert a basic type to a class type data.
  • 43. Short Answer Questions  Why is it necessary to overload and operator?  Operator overloading allows us to provide new implementations for existing operators. Using operator overloading one can perform the operation on the user defined data types in the same way as that of built-in data types.  Example: Two integer values can be added as c = a + b. With the use of operator overloading the + operator can also be used to perform addition of two complex numbers as: C3 = C1 + C2 where C1, C2 and C3 are the objects of class complex.
  • 44. Short Answer Questions  When is a friend function compulsory? Give example.  Friend function is used in a situation where we need to use two different types of operands for a binary operator. One an object and another a built-in data type. A = 2 + B  Here the statement will not be executed by the member functions as the left hand operand which is responsible for invoking the member function is not the object of the same class. However the friend function allows the statement to be executed.
  • 45. Short Answer Questions  A friend function cannot be used to overload the assignment operator = . Explain why?  In the assignment operator, the right hand operand is source and lefthand operand is the target of assignment. When we overload assignment operator as member function then the Lvalue becomes the object for which the assignment operator is called and the Rvalue object is passed as parameter. If the Rvalue is constant then by using the constructor that value can be converted into object and then will be passed as parameter to the assignment operator. But in case of friend function both the Lvalue and Rvalue needs to be passed as parameter. If the Lvalue is constant then it gets converted into the class object by constructor which results in changing the constant value which is not allowed/illegal. Hence, to avoid modifying constant as Lvalue assignment operator was restricted to be overloaded as friend function.
  • 46. Short Answer Questions  Name the operators that cannot be overloaded.  Class member access operators (., .*)  Scope resolution operator (::)  Size operator (sizeof )  Conditional operator (?:)  Name the operators that cannot be overloaded using friend function.  Assignment operator ( = )  Function call operator ( )  Subscripting operator [ ]  Class member access operator ( -> )
  • 47. Short Answer Questions  What is conversion function. How is it created. Explain its syntax.  The conversion function is the overloaded casting operator that is used to convert a class type data to basic type data.  Syntax: Operator typename() { ........... ........... }  This function converts a class type data to typename.  Operator int() converts a class type object to type int.
  • 48. Short Answer Questions  A class alpha has a constructor as follows: Alpha ( int a, double b); Can we use this constructor to convert types?  No, we cannot use this constructor to convert types because when the constructors are used for the type conversion it take a single argument whose type is to be converted.  In the given example the alpha constructor is having two arguments int and double.
  • 49. Short Answer Questions  We have two classes X and Y. If a is an object of X and b is an object of Y and we want to say a = b; what type of conversion routine should be used and where?  To perform the conversion a = b we use the type casting operator function in the source class. The conversion takes place in theY class and the result is given to the X class.
  • 50. References  Object Oriented Programming with C++ by E. Balagurusamy.