SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
Lahiru Dilshan
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
Sachin Sharma
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Friend function
Friend functionFriend function
Friend function
zindadili
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Burhan Ahmed
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
Arpita Patel
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
Zohaib Ahmed
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
Lahiru Dilshan
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Friend function
Friend functionFriend function
Friend function
zindadili
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Burhan Ahmed
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
Arpita Patel
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
Zohaib Ahmed
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 

Similar to Operator overloading (20)

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 overloading2
zindadili
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
Princess Sam
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
esuEthopi
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
Mukund Trivedi
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
Princess Sam
 
22 scheme OOPs with C++ BCS306B_module3.pdf
22 scheme  OOPs with C++ BCS306B_module3.pdf22 scheme  OOPs with C++ BCS306B_module3.pdf
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Lecture5
Lecture5Lecture5
Lecture5
ravifeelings
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
Basics _of_Operator Overloading_Somesh_Kumar_SSTCBasics _of_Operator Overloading_Somesh_Kumar_SSTC
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
 
Array Cont
Array ContArray Cont
Array Cont
Ashutosh Srivasatava
 
Bc0037
Bc0037Bc0037
Bc0037
hayerpa
 
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
rajshreemuthiah
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ramya marichamy
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
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 overloading2
zindadili
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
Princess Sam
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
esuEthopi
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
Princess Sam
 
22 scheme OOPs with C++ BCS306B_module3.pdf
22 scheme  OOPs with C++ BCS306B_module3.pdf22 scheme  OOPs with C++ BCS306B_module3.pdf
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
Basics _of_Operator Overloading_Somesh_Kumar_SSTCBasics _of_Operator Overloading_Somesh_Kumar_SSTC
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
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
rajshreemuthiah
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Ad

More from Pranali Chaudhari (8)

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

Recently uploaded (20)

Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 

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.