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

More Related Content

What's hot (20)

PPTX
Member Function in C++
NikitaKaur10
 
PPTX
Data Type Conversion in C++
Danial Mirza
 
PPTX
Constructors in C++
RubaNagarajan
 
PDF
Constructor and Destructor
Kamal Acharya
 
PDF
sparse matrix in data structure
MAHALAKSHMI P
 
PPTX
Constructor and destructor
Shubham Vishwambhar
 
PPT
Method overriding
Azaz Maverick
 
PPTX
Oop c++class(final).ppt
Alok Kumar
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
Operator overloading
Ramish Suleman
 
PPTX
Static keyword ppt
Vinod Kumar
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPTX
Strings in C language
P M Patil
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
parameter passing in c#
khush_boo31
 
PPTX
Encapsulation C++
Hashim Hashim
 
PPTX
File in C language
Manash Kumar Mondal
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPSX
Files in c++
Selvin Josy Bai Somu
 
PPTX
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 
Member Function in C++
NikitaKaur10
 
Data Type Conversion in C++
Danial Mirza
 
Constructors in C++
RubaNagarajan
 
Constructor and Destructor
Kamal Acharya
 
sparse matrix in data structure
MAHALAKSHMI P
 
Constructor and destructor
Shubham Vishwambhar
 
Method overriding
Azaz Maverick
 
Oop c++class(final).ppt
Alok Kumar
 
Union in C programming
Kamal Acharya
 
Operator overloading
Ramish Suleman
 
Static keyword ppt
Vinod Kumar
 
classes and objects in C++
HalaiHansaika
 
Strings in C language
P M Patil
 
Functions in c++
Rokonuzzaman Rony
 
parameter passing in c#
khush_boo31
 
Encapsulation C++
Hashim Hashim
 
File in C language
Manash Kumar Mondal
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Files in c++
Selvin Josy Bai Somu
 
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 

Similar to Operator overloading (20)

PDF
overloading in C++
Prof Ansari
 
PDF
Operator_Overloaing_Type_Conversion_OOPC(C++)
Yaksh Jethva
 
PPTX
Operator overloading2
zindadili
 
PPT
Lec 26.27-operator overloading
Princess Sam
 
PDF
Ch-4-Operator Overloading.pdf
esuEthopi
 
PPT
3d7b7 session4 c++
Mukund Trivedi
 
PPT
Lec 28 - operator overloading
Princess Sam
 
PDF
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
PPT
C++ Function
Hajar
 
PPT
Lecture5
ravifeelings
 
PPTX
Classes function overloading
ankush_kumar
 
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
PDF
Functions in C++
Pranali Chaudhari
 
DOCX
Array Cont
Ashutosh Srivasatava
 
DOCX
Bc0037
hayerpa
 
PPTX
Operator overloading and type conversion in cpp
rajshreemuthiah
 
PPTX
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
PPTX
Operator overloading
ramya marichamy
 
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
PPT
C++ tutorials
Divyanshu Dubey
 
overloading in C++
Prof Ansari
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Yaksh Jethva
 
Operator overloading2
zindadili
 
Lec 26.27-operator overloading
Princess Sam
 
Ch-4-Operator Overloading.pdf
esuEthopi
 
3d7b7 session4 c++
Mukund Trivedi
 
Lec 28 - operator overloading
Princess Sam
 
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
C++ Function
Hajar
 
Lecture5
ravifeelings
 
Classes function overloading
ankush_kumar
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
Functions in C++
Pranali Chaudhari
 
Bc0037
hayerpa
 
Operator overloading and type conversion in cpp
rajshreemuthiah
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
Operator overloading
ramya marichamy
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C++ tutorials
Divyanshu Dubey
 
Ad

More from Pranali Chaudhari (8)

PDF
Exception handling
Pranali Chaudhari
 
PDF
Files and streams
Pranali Chaudhari
 
PDF
Templates
Pranali Chaudhari
 
PDF
Managing I/O in c++
Pranali Chaudhari
 
PDF
Inheritance
Pranali Chaudhari
 
PDF
Constructors destructors
Pranali Chaudhari
 
PDF
Introduction to C++
Pranali Chaudhari
 
PDF
Object oriented concepts
Pranali Chaudhari
 
Exception handling
Pranali Chaudhari
 
Files and streams
Pranali Chaudhari
 
Managing I/O in c++
Pranali Chaudhari
 
Inheritance
Pranali Chaudhari
 
Constructors destructors
Pranali Chaudhari
 
Introduction to C++
Pranali Chaudhari
 
Object oriented concepts
Pranali Chaudhari
 
Ad

Recently uploaded (20)

PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
Snet+Pro+Service+Software_SNET+Pro+2+Instructions.pptx
jenilsatikuvar1
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PDF
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PPTX
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
PPTX
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
Day2 B2 Best.pptx
helenjenefa1
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Snet+Pro+Service+Software_SNET+Pro+2+Instructions.pptx
jenilsatikuvar1
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 

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.