SlideShare uma empresa Scribd logo
1 de 54
Operator OverloadingOperator Overloading
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Object oriented ProgrammingObject oriented Programming
with C++with C++
Operator overloading
• It is one of the many exciting features of C+
+.
• Important technique that has enhanced the
power of extensibility of C++.
• C++ tries to make the user-defined data
types behave in much the same way as the
built-in types.
• C++ permits us to add two variables of user-
defined types with the same syntax that is
applied to the basic types.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Operator overloading
• Addition (+) operator can work on
operands of type char, int, float & double.
• However, if s1, s2, s3 are objects of the class
string, the we can write the statement,
s3 = s1 + s2;
• This means C++ has the ability to provide
the operators with a special meaning for a
data type.
• Mechanism of giving special meaning to an
operator is known as operator overloading.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Operator overloading
• Operator – is a symbol that indicates an
operation.
• Overloading – assigning different meanings
to an operation, depending upon the
context.
• For example: input(>>)/output(<<)
operator
– The built-in definition of the operator << is for
shifting of bits.
– It is also used for displaying the values of
various data types.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Operator overloading
• We can overload all C++ operator except
the following:
– Class member access operator (. , .*)
– Scope resolution operator(::)
– Size operator (sizeof)
– Conditional operator(?:)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Defining operator overloading
• The general form of an operator function is:
return-type class-name :: operator op (argList)
{
function body // task defined.
}
– where return-type is the type of value
returned by the specified operation.
– op is the operator being overloaded.
– operator op is the function name, where
operator is a keyword.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Operator overloading
• When an operator is overloaded, the
produced symbol called operator function
name.
• operator function should be either member
function or friend function.
• Friend function requires one argument for
unary operator and two for binary
operators.
• Member function requires one arguments
for binary operators and zero arguments for
unary operators.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Operator overloading
Process of overloading involves following steps:
1. Creates the class that defines the data type
i.e. to be used in the overloading operation.
2.Declare the operator function operator op()
in the public part of the class. It may be
either a member function or friend function.
3.Define the operator function to implement
the required operations.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading unary operator
• Overloading devoid of explicit argument to
an operator function is called as unary
operator overloading.
• The operator ++, -- and – are unary
operators.
• ++ and -- can be used as prefix or suffix with
the function.
• These operators have only single operand.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Unary Operators (-)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
using namespace std;
class UnaryOp
{
int x,y,z;
public:
UnaryOp()
{
x=0;
y=0;
z=0;
}
UnaryOp(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void display()
{
cout<<"nnt"<<x<<" "<<y<<" "<<z;
}
// Overloaded minus (-) operator
void operator- ();
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
void UnaryOp :: operator- ()
{
x= -x;
y= -y;
z= -z;
}
int main()
{
UnaryOp un(10,-40,70);
cout<<"nnNumbers are :::n";
un.display();
-un; // call unary minus operator function
cout<<"nnNumbers are after overloaded minus (-) operator :::n";
un.display(); // display un
return 0;
}
Output :
Numbers are :::
10 -40 70
Numbers are after overloaded minus (-) operator :::
-10 40 -70
Overloading Unary Operators (-)
Overloading Unary Operators (++/--)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include<iostream>
using namespace std;
class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}
void operator--()
{
a=--a;
b=--b;
}
void display()
{
cout<<a<<" +t"<<b<<"i"<<endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
int main()
{
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Numbern";
obj.display();
obj--;
cout<<"Decrement Complex Numbern";
obj.display();
return 0;
}
Output:
Enter the Two Numbers:
2
3
Increment Complex Number
3 + 4i
Decrement Complex Number
2 + 3i
Overloading Unary Operators (++/--)
Overloading Binary Operators (+)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
using namespace std;
class Complex
{
double real;
double imag;
public:
Complex () {}
Complex (double, double);
Complex operator + (Complex);
void print();
};
Complex::Complex (double r, double i)
{
real = r;
imag = i;
}
Complex Complex::operator+ (Complex param)
{
Complex temp;
temp.real = real + param.real;
temp.imag = imag + param.imag;
return (temp);
}
Overloading Binary Operators (+)
Complex Complex::operator+ (Complex param)
{
Complex temp;
temp.real = real + param.real;
temp.imag = imag + param.imag;
return (temp);
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Complex C1 (3.1, 1.5);
Complex C2 (1.2, 2.2);
Complex C3;
C3 = C1 + C2;
Two objects c1 and c2 are two passed as an argument. c1 is
treated as first operand and c2 is treated as second
operand of the + operator.
Programming Exercise:
Write a program to find out factorial of given number
using ‘*’ function.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
void Complex::print()
{
cout << real << " + i" << imag << endl;
}
int main ()
{
Complex c1 (3.1, 1.5);
Complex c2 (1.2, 2.2);
Complex c3;
c3 = c1 + c2; //use overloaded + operator
//c3 = c1.operator+(c2);
c1.print();
c2.print();
c3.print();
return 0;
}
Output :
3.1 + i 1.5
1.2 + i 2.2
4.3 + i 3.7
Overloading Binary Operators (+)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Binary Operators (+) using friend function
#include <iostream>
using namespace std;
class Complex
{
double real;
double imag;
public:
Complex () {}
Complex (double, double);
friend Complex operator + (Complex, Complex);
void print();
};
Complex::Complex (double r, double i)
{
real = r;
imag = i;
}
Complex operator+ (Complex p, Complex q)
{
Complex temp;
temp.real = p.real + q.real;
temp.imag = p.imag + q.imag;
return (temp);
}
Complex operator+ (Complex p, Complex q)
{
Complex temp;
temp.real = p.real + q.real;
temp.imag = p.imag + q.imag;
return (temp);
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Complex C1 (3.1, 1.5);
Complex C2 (1.2, 2.2);
Complex C3;
C3 = C1 + C2;
Overloading Binary Operators (+) using friend function
Two objects c1 and c2 are two passed as an argument. c1 is
treated as first operand and c2 is treated as second
operand of the + operator.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Output :
3.1 + i 1.5
1.2 + i 2.2
4.3 + i 3.7
Overloading Binary Operators (+) using friend function
void Complex::print()
{
cout << real << " + i" << imag << endl;
}
int main ()
{
Complex c1 (3.1, 1.5);
Complex c2 (1.2, 2.2);
Complex c3;
c3 = c1 + c2; //use overloaded + operator
//c3 = operator+(c1, c2);
c1.print();
c2.print();
c3.print();
return 0;
}
Why to use friend function?
• Consider a situation where we need to use
two different types of operands for binary
operator.
• One an object and another a built-in –type
data.
• d2 = d1 + 50;
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Why to use friend function?
#include<iostream>
using namespace std;
class demo
{
int num;
public:
demo()
{
num = 0;
}
demo(int x)
{
num = x;
}
friend demo operator+(demo, int);
void show(char *s)
{
cout << "num of object "<< s << "=" << num <<endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Why to use friend function?
demo operator+(demo T, int x)
{
demo temp;
temp.num = T.num + x;
return temp;
}
int main()
{
demo d1(100),d2;
d2 = d1 + 50;
d1.show ("d1");
d2.show ("d2");
return 0;
}
Output :
num of object d1=100
num of object d2=150
Overloading Input/output operator
• C++ is able to input and output the built-in data
types using the stream extraction operator >> and
the stream insertion operator <<.
• Overloaded to perform input/output for user
defined data types.
• Left Operand will be of types ostream & and
istream &.
• Function overloading this operator must be a
Non-Member function because left operand is not
an Object of the class.
• It must be a friend function to access private data
members.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Input/output operator
#include<iostream>
using namespace std;
class time
{
int hr,min,sec;
public:
time()
{
hr=0, min=0; sec=0;
}
time(int h,int m, int s)
{
hr=h, min=m; sec=s;
}
friend ostream& operator << (ostream &out, time &tm);
//overloading '<<' operator
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Input/output operator
ostream& operator << (ostream &out, time &tm) //operator function
{
out << "Time is " << tm.hr << "hour : " << tm.min << "min : "
<< tm.sec << "sec";
return out;
}
int main()
{
time tm(3,15,45);
cout << tm;
return 0;
}
Output:
Time is 3 hour : 15 min : 45 sec
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Input/output operator
#include<iostream>
using namespace std;
class dist
{
int feet;
int inch;
public:
dist()
{
feet = 0;
inch = 0;
}
dist(int a, int b)
{
feet = a;
inch = b;
}
friend ostream& operator <<(ostream &out, dist &d);
friend istream& operator >>(istream &in, dist &d);
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Input/output operator
ostream& operator <<(ostream &out, dist &d)
{
out <<"Feet::" << d.feet << " Inch::" << d.inch <<endl;
return out;
}
istream& operator >>(istream &in, dist &d)
{
in >> d.feet >> d.inch;
return in;
}
int main()
{
dist d1(11, 10), d2(5, 11), d3;
cout <<"Enter the values of object:"<<endl;
cin >> d3;
cout <<"First Distance :"<<d1<<endl;
cout <<"Second Distance :"<<d2<<endl;
cout <<"Third Distance :"<<d3<<endl;
return 0;
}
Output ::
Enter the values of object:
11
12
First Distance :Feet::11 Inch::10
Second Distance :Feet::5 Inch::11
Third Distance :Feet::11 Inch::12
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Assignment(=) operator
#include<iostream>
using namespace std;
class dist
{
int feet;
int inch;
public:
dist()
{
feet = 0;
inch = 0;
}
dist(int a, int b)
{
feet = a;
inch = b;
}
void operator = (dist &d)
{
feet = d.feet;
inch = d.inch;
}
void display ()
{
cout << "Feet: " << feet << " Inch: " << inch << endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Assignment(=) operator
int main()
{
dist d1(11, 10), d2(5, 11);
cout <<"First Distance :"<< endl;
d1.display ();
cout <<"Second Distance :"<< endl;
d2.display ();
//use of asssignment operator
d1 = d2;
cout <<"First Distance :"<< endl;
d1.display ();
return 0;
}
Output::
First Distance :
Feet: 11 Inch: 10
Second Distance :
Feet: 5 Inch: 11
First Distance :
Feet: 5 Inch: 11
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Arithmetic assignment (+=) operator
#include<iostream>
using namespace std;
class dist
{
int feet;
int inch;
public:
dist()
{
feet = 0;
inch = 0;
}
dist(int a, int b)
{
feet = a;
inch = b;
}
void display ()
{
cout << "Feet: " << feet << " Inch: " << inch << endl;
}
void operator += (dist &d)
{
feet += d.feet;
inch += d.inch;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Arithmetic assignment (+=) operator
int main()
{
dist d1(11, 10), d2(5, 11);
cout <<"First Distance :"<< endl;
d1.display ();
cout <<"Second Distance :"<< endl;
d2.display ();
d1 += d2;
cout <<"First Distance :"<< endl;
d1.display ();
return 0;
}
Output ::
First Distance :
Feet: 11 Inch: 10
Second Distance :
Feet: 5 Inch: 11
First Distance :
Feet: 16 Inch: 21
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Subscript ([]) operator
#include <iostream>
using namespace std;
class demo
{
int *p;
public:
demo(int n)
{
p = new int [n];
for(int i = 0; i < n; i++)
p[i] = i + 1;
}
int operator[](int x)
{
return p[x];
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Subscript ([]) operator
int main()
{
demo d(5);
for(int i = 0; i < 5; i++)
cout << d[i]<< " ";
return 0;
}
Output ::
1 2 3 4 5 Statement d[i] is interpreted internally as
d.operator[](x). In each iteration of for loop
we call the overloaded operator function []
and pass the value of 'i' which returns the
corresponding array elements.
Statement d[i] is interpreted internally as
d.operator[](x). In each iteration of for loop
we call the overloaded operator function []
and pass the value of 'i' which returns the
corresponding array elements.
Overloading relational operator
• There are various relational operators supported
by c++ language which can be used to compare c+
+ built-in data types.
• For Example:
– Equality (==)
– Less than (<)
– Less than or equal to (<=)
– Greater than (>)
– Greater than or equal to (>=)
– Inequality (!=)
• We can overload any of these operators, which
can be used to compare the objects of a class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading relational operator
#include<iostream>
using namespace std;
class dist
{
int feet;
int inch;
public:
dist(int a, int b)
{
feet = a;
inch = b;
}
void display ()
{
cout << "Feet: " << feet << " Inch: " << inch << endl;
}
bool operator < (dist d)
{
if(feet < d.feet)
{
return true;
}
if(feet == d.feet && inch < d.inch)
{
return true;
}
return false;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading relational operator
int main()
{
dist d1(11, 10), d2(5, 11);
cout <<"First Distance :"<< endl;
d1.display ();
cout <<"Second Distance :"<< endl;
d2.display ();
if (d1 < d2)
cout << "d1 is less than d2." << endl;
else
cout << "d1 is greater than (or equal to) d2." << endl;
return 0;
}
Output::
First Distance :
Feet: 11 Inch: 10
Second Distance :
Feet: 5 Inch: 11
d1 is greater than (or equal to) d2.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading pointer-to-member (->) operator
#include<iostream>
using namespace std;
class test
{
int num;
public:
test (int j)
{
num = j;
}
void display()
{
cout << "num is " << num << endl;
}
test *operator ->(void)
{
return this;
}
};
The ‘this’ pointer is passed as a hidden argument to
all non-static member function calls and is available
as a local variable within the body of all non-static
functions. ‘this’ pointer is a constant pointer that
holds the memory address of the current object.
The ‘this’ pointer is passed as a hidden argument to
all non-static member function calls and is available
as a local variable within the body of all non-static
functions. ‘this’ pointer is a constant pointer that
holds the memory address of the current object.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading pointer-to-member (->) operator
int main()
{
test T (5);
T.display (); //acessing display() normally
test *ptr = &T;
ptr -> display(); //using class pointer
T -> display(); //using overloaded operator
return 0;
}
Output::
num is 5
num is 5
num is 5
Rules for overloading operator
• Only existing operators can be overloaded. We
cannot create a new operator.
• Overloaded operator should contain one operand
of user-defined data type.
– Overloading operators are only for classes. We cannot
overload the operator for built-in data types.
• Overloaded operators have the same syntax as the
original operator.
• Operator overloading is applicable within the
scope (extent) in which overloading occurs.
• Binary operators overloaded through a member
function take one explicit argument and those
which are overloaded through a friend function
take two explicit arguments.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Rules for overloading operator
• Overloading of an operator cannot change the
basic idea of an operator.
– For example A and B are objects. The following
statement
– A+=B;
– assigns addition of objects A and B to A.
– Overloaded operator must carry the same task like
original operator according to the language.
– Following statement must perform the same operation
like the last statement.
– A=A+B;
• Overloading of an operator must never change its
natural meaning.
– An overloaded operator + can be used for subtraction
of two objects, but this type of code decreases the
utility of the program.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Type Conversion
• C++ allows to convert one data type to another
e.g. int ›››› float
• For example:
int m ;
float x = 3.1419;
m = x;
• convert x to an integer before its values is
assigned to m. Thus, fractional part is truncated.
• C++ already knows how to convert between built-
in data types.
• However, it does not know how to convert any
user-defined classes
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Type Conversion
There are three possibilities of data conversion as
given below:
1. Conversion from basic-data type to user-defined
data type.
2. Conversion from class type to basic-data type.
3. Conversion from one class type to another class
type.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Type Conversion
Basic to Class data type conversion:
• Conversion from basic to class type is easily
carried out.
• It is automatically done by compiler with the
help of in-built routines or by typecasting.
• Left-hand operand of = sign is always class type
and right-hand operand is always basic type.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Conversion from Basic to class-type:
#include<iostream>
using namespace std;
class time
{
int hrs;
int min;
public:
time()
{
hrs = 0;
min = 0;
}
time(int t)
{
hrs = t / 60;
min = t % 60;
}
void display ()
{
cout << hrs << "::" << min <<endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Conversion from Basic to class-type:
int main()
{
time T;
int duration = 85;
T = duration;
T.display();
return 0;
}
Output ::
1::25
Class to basic-data type conversion :
• In this conversion, the programmer explicitly tell
the compiler how to perform conversion from
class to basic type.
• These instructions are written in a member
function.
• Such function is known as overloading of type
cast operators.
• Left-hand operand is always Basic type and right-
hand operand is always class type.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Type Conversion
Class-type to basic-data type conversion :
• While carrying this conversion, the
statement should satisfy the following
conditions:
1. The conversion function should not have any
argument.
2. Do not mention return type.
3. It should be class member function.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Type Conversion
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Conversion from Class to Basic-type:
#include<iostream>
using namespace std;
class Distance
{
int length;
public:
Distance (int n)
{
length = n;
}
operator int()
{
return length;
}
};
int main()
{
Distance d(12);
int len = d; // implicit
int hei = (int) d; // Explicit
cout << hei;
return 0;
}
We have converted Distance class
object into integer type. When the
statement int len = d; executes, the
compiler searches for a function
which can convert an object of
Distance class type to int type.
We have converted Distance class
object into integer type. When the
statement int len = d; executes, the
compiler searches for a function
which can convert an object of
Distance class type to int type.
Type Conversion
Conversion from one Class to another Class Type:
• When an object of one class is passed to another
class, it is necessary clear-cut instructions to the
compiler.
• How to make conversion between these two
user defined data types?
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Conversion from one class to another class-type:
#include<iostream>
using namespace std;
class nInch
{
int inch;
public:
nInch (int n)
{
inch = n;
}
int getInch()
{
return inch;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Conversion from one class to another class-type:
class nFeet
{
int feet;
public:
nFeet (int n)
{
feet = n;
}
operator nInch()
{
return nInch(feet * 12);
}
friend void printInch(nInch m);
};
void printInch(nInch m)
{
cout << m.getInch ();
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Conversion from one class to another class-type:
int main()
{
int n;
cout << "Enter feet: " << endl;
cin >> n;
nFeet f(n);
cout << "Inch is : ";
printInch (f);
return 0;
}
Output:
Enter feet:
2
Inch is : 24
To beTo be
continued…..continued…..

Mais conteúdo relacionado

Mais procurados

friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vishal Patil
 
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
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming LanguageMahantesh Devoor
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaRahulAnanda1
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 

Mais procurados (20)

friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Structure in C
Structure in CStructure in C
Structure in C
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Inline function
Inline functionInline function
Inline function
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
class and objects
class and objectsclass and objects
class and objects
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 

Destaque

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cppgourav kottawar
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversionsAmogh Kalyanshetti
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programAAKASH KUMAR
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 

Destaque (6)

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversions
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 

Semelhante a Operator Overloading

Semelhante a Operator Overloading (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Bc0037
Bc0037Bc0037
Bc0037
 
Cpp (C++)
Cpp (C++)Cpp (C++)
Cpp (C++)
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
3. Polymorphism.pptx
3. Polymorphism.pptx3. Polymorphism.pptx
3. Polymorphism.pptx
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
C++ theory
C++ theoryC++ theory
C++ theory
 
C#2
C#2C#2
C#2
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
 

Mais de Nilesh Dalvi

Mais de Nilesh Dalvi (20)

14. Linked List
14. Linked List14. Linked List
14. Linked List
 
13. Queue
13. Queue13. Queue
13. Queue
 
12. Stack
12. Stack12. Stack
12. Stack
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
8. String
8. String8. String
8. String
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Strings
StringsStrings
Strings
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Último

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Último (20)

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Operator Overloading

  • 1. Operator OverloadingOperator Overloading By Nilesh Dalvi Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Object oriented ProgrammingObject oriented Programming with C++with C++
  • 2. Operator overloading • It is one of the many exciting features of C+ +. • Important technique that has enhanced the power of extensibility of C++. • C++ tries to make the user-defined data types behave in much the same way as the built-in types. • C++ permits us to add two variables of user- defined types with the same syntax that is applied to the basic types. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3. Operator overloading • Addition (+) operator can work on operands of type char, int, float & double. • However, if s1, s2, s3 are objects of the class string, the we can write the statement, s3 = s1 + s2; • This means C++ has the ability to provide the operators with a special meaning for a data type. • Mechanism of giving special meaning to an operator is known as operator overloading. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 4. Operator overloading • Operator – is a symbol that indicates an operation. • Overloading – assigning different meanings to an operation, depending upon the context. • For example: input(>>)/output(<<) operator – The built-in definition of the operator << is for shifting of bits. – It is also used for displaying the values of various data types. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 5. Operator overloading • We can overload all C++ operator except the following: – Class member access operator (. , .*) – Scope resolution operator(::) – Size operator (sizeof) – Conditional operator(?:) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 6. Defining operator overloading • The general form of an operator function is: return-type class-name :: operator op (argList) { function body // task defined. } – where return-type is the type of value returned by the specified operation. – op is the operator being overloaded. – operator op is the function name, where operator is a keyword. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 7. Operator overloading • When an operator is overloaded, the produced symbol called operator function name. • operator function should be either member function or friend function. • Friend function requires one argument for unary operator and two for binary operators. • Member function requires one arguments for binary operators and zero arguments for unary operators. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 8. Operator overloading Process of overloading involves following steps: 1. Creates the class that defines the data type i.e. to be used in the overloading operation. 2.Declare the operator function operator op() in the public part of the class. It may be either a member function or friend function. 3.Define the operator function to implement the required operations. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 9. Overloading unary operator • Overloading devoid of explicit argument to an operator function is called as unary operator overloading. • The operator ++, -- and – are unary operators. • ++ and -- can be used as prefix or suffix with the function. • These operators have only single operand. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 10. Overloading Unary Operators (-) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> using namespace std; class UnaryOp { int x,y,z; public: UnaryOp() { x=0; y=0; z=0; } UnaryOp(int a,int b,int c) { x=a; y=b; z=c; } void display() { cout<<"nnt"<<x<<" "<<y<<" "<<z; } // Overloaded minus (-) operator void operator- (); };
  • 11. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). void UnaryOp :: operator- () { x= -x; y= -y; z= -z; } int main() { UnaryOp un(10,-40,70); cout<<"nnNumbers are :::n"; un.display(); -un; // call unary minus operator function cout<<"nnNumbers are after overloaded minus (-) operator :::n"; un.display(); // display un return 0; } Output : Numbers are ::: 10 -40 70 Numbers are after overloaded minus (-) operator ::: -10 40 -70 Overloading Unary Operators (-)
  • 12. Overloading Unary Operators (++/--) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include<iostream> using namespace std; class complex { int a,b,c; public: complex(){} void getvalue() { cout<<"Enter the Two Numbers:"; cin>>a>>b; } void operator++() { a=++a; b=++b; } void operator--() { a=--a; b=--b; } void display() { cout<<a<<" +t"<<b<<"i"<<endl; } };
  • 13. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). int main() { complex obj; obj.getvalue(); obj++; cout<<"Increment Complex Numbern"; obj.display(); obj--; cout<<"Decrement Complex Numbern"; obj.display(); return 0; } Output: Enter the Two Numbers: 2 3 Increment Complex Number 3 + 4i Decrement Complex Number 2 + 3i Overloading Unary Operators (++/--)
  • 14. Overloading Binary Operators (+) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> using namespace std; class Complex { double real; double imag; public: Complex () {} Complex (double, double); Complex operator + (Complex); void print(); }; Complex::Complex (double r, double i) { real = r; imag = i; } Complex Complex::operator+ (Complex param) { Complex temp; temp.real = real + param.real; temp.imag = imag + param.imag; return (temp); }
  • 15. Overloading Binary Operators (+) Complex Complex::operator+ (Complex param) { Complex temp; temp.real = real + param.real; temp.imag = imag + param.imag; return (temp); } Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Complex C1 (3.1, 1.5); Complex C2 (1.2, 2.2); Complex C3; C3 = C1 + C2; Two objects c1 and c2 are two passed as an argument. c1 is treated as first operand and c2 is treated as second operand of the + operator.
  • 16. Programming Exercise: Write a program to find out factorial of given number using ‘*’ function. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 17. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). void Complex::print() { cout << real << " + i" << imag << endl; } int main () { Complex c1 (3.1, 1.5); Complex c2 (1.2, 2.2); Complex c3; c3 = c1 + c2; //use overloaded + operator //c3 = c1.operator+(c2); c1.print(); c2.print(); c3.print(); return 0; } Output : 3.1 + i 1.5 1.2 + i 2.2 4.3 + i 3.7 Overloading Binary Operators (+)
  • 18. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Binary Operators (+) using friend function #include <iostream> using namespace std; class Complex { double real; double imag; public: Complex () {} Complex (double, double); friend Complex operator + (Complex, Complex); void print(); }; Complex::Complex (double r, double i) { real = r; imag = i; } Complex operator+ (Complex p, Complex q) { Complex temp; temp.real = p.real + q.real; temp.imag = p.imag + q.imag; return (temp); }
  • 19. Complex operator+ (Complex p, Complex q) { Complex temp; temp.real = p.real + q.real; temp.imag = p.imag + q.imag; return (temp); } Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Complex C1 (3.1, 1.5); Complex C2 (1.2, 2.2); Complex C3; C3 = C1 + C2; Overloading Binary Operators (+) using friend function Two objects c1 and c2 are two passed as an argument. c1 is treated as first operand and c2 is treated as second operand of the + operator.
  • 20. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Output : 3.1 + i 1.5 1.2 + i 2.2 4.3 + i 3.7 Overloading Binary Operators (+) using friend function void Complex::print() { cout << real << " + i" << imag << endl; } int main () { Complex c1 (3.1, 1.5); Complex c2 (1.2, 2.2); Complex c3; c3 = c1 + c2; //use overloaded + operator //c3 = operator+(c1, c2); c1.print(); c2.print(); c3.print(); return 0; }
  • 21. Why to use friend function? • Consider a situation where we need to use two different types of operands for binary operator. • One an object and another a built-in –type data. • d2 = d1 + 50; Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 22. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Why to use friend function? #include<iostream> using namespace std; class demo { int num; public: demo() { num = 0; } demo(int x) { num = x; } friend demo operator+(demo, int); void show(char *s) { cout << "num of object "<< s << "=" << num <<endl; } };
  • 23. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Why to use friend function? demo operator+(demo T, int x) { demo temp; temp.num = T.num + x; return temp; } int main() { demo d1(100),d2; d2 = d1 + 50; d1.show ("d1"); d2.show ("d2"); return 0; } Output : num of object d1=100 num of object d2=150
  • 24. Overloading Input/output operator • C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. • Overloaded to perform input/output for user defined data types. • Left Operand will be of types ostream & and istream &. • Function overloading this operator must be a Non-Member function because left operand is not an Object of the class. • It must be a friend function to access private data members. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 25. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Input/output operator #include<iostream> using namespace std; class time { int hr,min,sec; public: time() { hr=0, min=0; sec=0; } time(int h,int m, int s) { hr=h, min=m; sec=s; } friend ostream& operator << (ostream &out, time &tm); //overloading '<<' operator };
  • 26. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Input/output operator ostream& operator << (ostream &out, time &tm) //operator function { out << "Time is " << tm.hr << "hour : " << tm.min << "min : " << tm.sec << "sec"; return out; } int main() { time tm(3,15,45); cout << tm; return 0; } Output: Time is 3 hour : 15 min : 45 sec
  • 27. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Input/output operator #include<iostream> using namespace std; class dist { int feet; int inch; public: dist() { feet = 0; inch = 0; } dist(int a, int b) { feet = a; inch = b; } friend ostream& operator <<(ostream &out, dist &d); friend istream& operator >>(istream &in, dist &d); };
  • 28. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Input/output operator ostream& operator <<(ostream &out, dist &d) { out <<"Feet::" << d.feet << " Inch::" << d.inch <<endl; return out; } istream& operator >>(istream &in, dist &d) { in >> d.feet >> d.inch; return in; } int main() { dist d1(11, 10), d2(5, 11), d3; cout <<"Enter the values of object:"<<endl; cin >> d3; cout <<"First Distance :"<<d1<<endl; cout <<"Second Distance :"<<d2<<endl; cout <<"Third Distance :"<<d3<<endl; return 0; } Output :: Enter the values of object: 11 12 First Distance :Feet::11 Inch::10 Second Distance :Feet::5 Inch::11 Third Distance :Feet::11 Inch::12
  • 29. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Assignment(=) operator #include<iostream> using namespace std; class dist { int feet; int inch; public: dist() { feet = 0; inch = 0; } dist(int a, int b) { feet = a; inch = b; } void operator = (dist &d) { feet = d.feet; inch = d.inch; } void display () { cout << "Feet: " << feet << " Inch: " << inch << endl; } };
  • 30. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Assignment(=) operator int main() { dist d1(11, 10), d2(5, 11); cout <<"First Distance :"<< endl; d1.display (); cout <<"Second Distance :"<< endl; d2.display (); //use of asssignment operator d1 = d2; cout <<"First Distance :"<< endl; d1.display (); return 0; } Output:: First Distance : Feet: 11 Inch: 10 Second Distance : Feet: 5 Inch: 11 First Distance : Feet: 5 Inch: 11
  • 31. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Arithmetic assignment (+=) operator #include<iostream> using namespace std; class dist { int feet; int inch; public: dist() { feet = 0; inch = 0; } dist(int a, int b) { feet = a; inch = b; } void display () { cout << "Feet: " << feet << " Inch: " << inch << endl; } void operator += (dist &d) { feet += d.feet; inch += d.inch; } };
  • 32. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Arithmetic assignment (+=) operator int main() { dist d1(11, 10), d2(5, 11); cout <<"First Distance :"<< endl; d1.display (); cout <<"Second Distance :"<< endl; d2.display (); d1 += d2; cout <<"First Distance :"<< endl; d1.display (); return 0; } Output :: First Distance : Feet: 11 Inch: 10 Second Distance : Feet: 5 Inch: 11 First Distance : Feet: 16 Inch: 21
  • 33. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Subscript ([]) operator #include <iostream> using namespace std; class demo { int *p; public: demo(int n) { p = new int [n]; for(int i = 0; i < n; i++) p[i] = i + 1; } int operator[](int x) { return p[x]; } };
  • 34. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading Subscript ([]) operator int main() { demo d(5); for(int i = 0; i < 5; i++) cout << d[i]<< " "; return 0; } Output :: 1 2 3 4 5 Statement d[i] is interpreted internally as d.operator[](x). In each iteration of for loop we call the overloaded operator function [] and pass the value of 'i' which returns the corresponding array elements. Statement d[i] is interpreted internally as d.operator[](x). In each iteration of for loop we call the overloaded operator function [] and pass the value of 'i' which returns the corresponding array elements.
  • 35. Overloading relational operator • There are various relational operators supported by c++ language which can be used to compare c+ + built-in data types. • For Example: – Equality (==) – Less than (<) – Less than or equal to (<=) – Greater than (>) – Greater than or equal to (>=) – Inequality (!=) • We can overload any of these operators, which can be used to compare the objects of a class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 36. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading relational operator #include<iostream> using namespace std; class dist { int feet; int inch; public: dist(int a, int b) { feet = a; inch = b; } void display () { cout << "Feet: " << feet << " Inch: " << inch << endl; } bool operator < (dist d) { if(feet < d.feet) { return true; } if(feet == d.feet && inch < d.inch) { return true; } return false; } };
  • 37. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading relational operator int main() { dist d1(11, 10), d2(5, 11); cout <<"First Distance :"<< endl; d1.display (); cout <<"Second Distance :"<< endl; d2.display (); if (d1 < d2) cout << "d1 is less than d2." << endl; else cout << "d1 is greater than (or equal to) d2." << endl; return 0; } Output:: First Distance : Feet: 11 Inch: 10 Second Distance : Feet: 5 Inch: 11 d1 is greater than (or equal to) d2.
  • 38. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading pointer-to-member (->) operator #include<iostream> using namespace std; class test { int num; public: test (int j) { num = j; } void display() { cout << "num is " << num << endl; } test *operator ->(void) { return this; } }; The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object.
  • 39. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Overloading pointer-to-member (->) operator int main() { test T (5); T.display (); //acessing display() normally test *ptr = &T; ptr -> display(); //using class pointer T -> display(); //using overloaded operator return 0; } Output:: num is 5 num is 5 num is 5
  • 40. Rules for overloading operator • Only existing operators can be overloaded. We cannot create a new operator. • Overloaded operator should contain one operand of user-defined data type. – Overloading operators are only for classes. We cannot overload the operator for built-in data types. • Overloaded operators have the same syntax as the original operator. • Operator overloading is applicable within the scope (extent) in which overloading occurs. • Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 41. Rules for overloading operator • Overloading of an operator cannot change the basic idea of an operator. – For example A and B are objects. The following statement – A+=B; – assigns addition of objects A and B to A. – Overloaded operator must carry the same task like original operator according to the language. – Following statement must perform the same operation like the last statement. – A=A+B; • Overloading of an operator must never change its natural meaning. – An overloaded operator + can be used for subtraction of two objects, but this type of code decreases the utility of the program. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 42. Type Conversion • C++ allows to convert one data type to another e.g. int ›››› float • For example: int m ; float x = 3.1419; m = x; • convert x to an integer before its values is assigned to m. Thus, fractional part is truncated. • C++ already knows how to convert between built- in data types. • However, it does not know how to convert any user-defined classes Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 43. Type Conversion There are three possibilities of data conversion as given below: 1. Conversion from basic-data type to user-defined data type. 2. Conversion from class type to basic-data type. 3. Conversion from one class type to another class type. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 44. Type Conversion Basic to Class data type conversion: • Conversion from basic to class type is easily carried out. • It is automatically done by compiler with the help of in-built routines or by typecasting. • Left-hand operand of = sign is always class type and right-hand operand is always basic type. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 45. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Conversion from Basic to class-type: #include<iostream> using namespace std; class time { int hrs; int min; public: time() { hrs = 0; min = 0; } time(int t) { hrs = t / 60; min = t % 60; } void display () { cout << hrs << "::" << min <<endl; } };
  • 46. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Conversion from Basic to class-type: int main() { time T; int duration = 85; T = duration; T.display(); return 0; } Output :: 1::25
  • 47. Class to basic-data type conversion : • In this conversion, the programmer explicitly tell the compiler how to perform conversion from class to basic type. • These instructions are written in a member function. • Such function is known as overloading of type cast operators. • Left-hand operand is always Basic type and right- hand operand is always class type. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Type Conversion
  • 48. Class-type to basic-data type conversion : • While carrying this conversion, the statement should satisfy the following conditions: 1. The conversion function should not have any argument. 2. Do not mention return type. 3. It should be class member function. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Type Conversion
  • 49. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Conversion from Class to Basic-type: #include<iostream> using namespace std; class Distance { int length; public: Distance (int n) { length = n; } operator int() { return length; } }; int main() { Distance d(12); int len = d; // implicit int hei = (int) d; // Explicit cout << hei; return 0; } We have converted Distance class object into integer type. When the statement int len = d; executes, the compiler searches for a function which can convert an object of Distance class type to int type. We have converted Distance class object into integer type. When the statement int len = d; executes, the compiler searches for a function which can convert an object of Distance class type to int type.
  • 50. Type Conversion Conversion from one Class to another Class Type: • When an object of one class is passed to another class, it is necessary clear-cut instructions to the compiler. • How to make conversion between these two user defined data types? Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 51. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Conversion from one class to another class-type: #include<iostream> using namespace std; class nInch { int inch; public: nInch (int n) { inch = n; } int getInch() { return inch; } };
  • 52. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Conversion from one class to another class-type: class nFeet { int feet; public: nFeet (int n) { feet = n; } operator nInch() { return nInch(feet * 12); } friend void printInch(nInch m); }; void printInch(nInch m) { cout << m.getInch (); }
  • 53. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Conversion from one class to another class-type: int main() { int n; cout << "Enter feet: " << endl; cin >> n; nFeet f(n); cout << "Inch is : "; printInch (f); return 0; } Output: Enter feet: 2 Inch is : 24

Notas do Editor

  1. n
  2. n
  3. n
  4. n
  5. n
  6. n
  7. n
  8. n
  9. n
  10. n
  11. n
  12. n
  13. n
  14. n
  15. n
  16. n
  17. n
  18. n
  19. n
  20. n
  21. n
  22. n
  23. n
  24. n
  25. n
  26. n
  27. n
  28. n
  29. n
  30. n
  31. n
  32. n
  33. n
  34. n
  35. n
  36. n
  37. n
  38. n
  39. n
  40. n
  41. n
  42. n
  43. n
  44. n
  45. n