0% found this document useful (0 votes)
47 views

Operator Overloading

The document discusses operator overloading in C++. It explains that operator overloading allows operators to operate on user-defined data types by giving special meaning to operators for those data types. Only existing operators can be overloaded, and their precedence, number of operands, and associativity cannot be changed. Operators can be overloaded as member functions or friend functions. Common operators that are overloaded include arithmetic operators, increment/decrement, insertion and extraction operators. The document provides examples of overloading unary minus, binary plus, and input/output operators.

Uploaded by

Ankita Kansal
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Operator Overloading

The document discusses operator overloading in C++. It explains that operator overloading allows operators to operate on user-defined data types by giving special meaning to operators for those data types. Only existing operators can be overloaded, and their precedence, number of operands, and associativity cannot be changed. Operators can be overloaded as member functions or friend functions. Common operators that are overloaded include arithmetic operators, increment/decrement, insertion and extraction operators. The document provides examples of overloading unary minus, binary plus, and input/output operators.

Uploaded by

Ankita Kansal
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
You are on page 1/ 47

Operator Overloading

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 1


What does it mean?
 Giving some special meaning to the
operators to enable them to operate on
user defined data types.

 Operator overloaded retains its original


meaning.
(say if * is overloaded to multiply two class objects
and can always be used multiply two numbers)

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 2


More about operator overloading
 Only existing operators can be
overloaded.
 Precedence, Number of operands and
associativity for any operator can not be
changed.
 Operator function can return any type of
data ( mostly it is made to return class objects
so that operators can be used in larger
expressions ).
 Operator function can take any data type
as arguments( mostly it takes class objects as
arguments for the above reason ).
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 3
Operators which cannot be overloaded
 Class member access operators ( . , .* )
 Scope resolution operator ( : : )
 Size operator ( sizeof )
 Conditional operator ( ? : )

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 4


Steps to overload an operator

1. A class is to be defined that defines the


data type for the operator to be
overloaded.
2. Declare the operator function in public
part of the class.
3. Define the operator function to implement
the required operations.

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 5


 The operator function can be defined either as
1. Member function
OR
2. Friend function (non member function)

Of the class which contains data members to be


operated by the operator.
The difference between two is that a friend function
will have 1 argument for unary operators and 2
argument for binary operators where as member
function has no argument for unary and 1 for
binary.
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 6
Defined as member function
1. Defined outside the class then
Return type operator op (arg_list); (Declaration)
And
Return type class_name :: operator op (arg_list)
Objects of
{ (definition)
this class is
Operator Specify
symboloperands other
Function
to be body….
+,_,*,/, etc
than one being
operated
} used to invoke
this op
2.Defined inside the class
Return_type operator op (arg_list)
{…function body }

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 7


Invoking overloaded operator
 Unary operators :
 op x or x op
 Binary operators :
 x op y

Interpreted as:
 Unary operators : operator op(x) in case of
friend functions.
 Binary operators : x.operator op(y) in case of
member functions.
operator op(x,y) in case of friend functions

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 8


Unary Minus ( -) is overloaded here
#include"iostream.h"
#include"conio.h"
class number
{
int no;
public:
void get_val()
{ cout<<endl<<"enter number";
cin>>no; }
void show()
{ cout<<endl<<"number is "<<no<<endl; }
void operator -()
{ no=-no; }
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 9
int main(void)
{
number m;
clrscr();
m.get_val();
m.show();
-m; // unary minus is called
return 0;
}

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 10


Output

enter number 25
number is 25 // entered number
number is -25 // negated number

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 11


Unary operator using friend function
 Remember that the above overloded operator
will not return any value.
 So statement like m1= -m; will not work.
 So for that we overload using friend function and
declared as follows:
friend void operator –( number &n);
 And defined as follows:
void operator–(number &n)
{
n.no = -n.no ;
}
 The arguments are passed by reference.

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 12


Overloading binary operator +
#include<iostream.h>
class point
{
int x, y;
public: Constructors
point () { x=0; y=0; }
point (int a, int b){ x=a; y=b; }
point operator +(point p ) // binary operator +
defined
{ point r;
r.x=x + p.x ;
r.y=y + p.y ;
return r;
}

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 13


void show()
{ cout<<endl<<"coordinates are"<<x<<"\t"<<y ; }
}; //class definition ends here

int main()
{
point p3,p1(12,23),p2(21,32);
clrscr();
p1.show();
p2.show();
p3=p1+p2; // same as p3=p1.operator+(p2)
p3.show();
return 0;
}

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 14


Output

 cordinates are 12 23
 cordinates are 21 32
 cordinates are 33 55

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 15


Defined as friend function

 Declared and defined like any friend


function.
 Number of operands to be passed as
arguments is same as number of
operands required for the operator.
That is for binary operation ,two arguments
are required and for unary single argument
is required.( DIFFERENT FROM OPERATOR
FUNCTION DEFINED AS MEMVER
FUNCTION)

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 16


#include<iostream.h>
#include<conio.h>
class number
{ int no;
public:
friend number operator * (number, number);
number()
{no=1;}
void display()
{ cout<<endl<<"number is "<<no<<endl;}
void get_val()
{
cout<<"enter number"<<endl;
cin>>no;}
};
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 17
number operator *(number n,number m)
{
number rslt;
rslt.no=n.no*m.no;
return rslt;
}
int main()
{
number n1,n2,n;
clrscr();
n1.display();
n2.display();
n1.get_val();
n2.get_val();
n=n1*n2;
n.display();
return 0; }
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 18
Output
number is 1
Due to constructor
number is 1
enter number
14
enter number
6
number is 84 Product of two number objects

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 19


More about operator overloading
 To overload unary increment(++) and unary
decrement (--), call by reference or pointers
should be used ( then only values of operands
will be really changed)
 Operators that can not be overloaded using
FRIEND function
1. Assignment (=)
2. Function call ( () )
3. Subscripting( [] )
4. Class member access operator( ->)

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 20


Minus ( -) is overloaded here
#include"iostream.h"
#include"conio.h"
class number
{
int no;
public:
void get_val()
{ cout<<endl<<"enter number";
cin>>no; }
void show()
{ cout<<endl<<"number is "<<no<<endl; }
void operator -()
{ no=-no; }
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 21
void operator -(number n1)
{ no=no-n1.no; } };
int main(void)
{
number m;
clrscr();
m.get_val();
m.show();
-m; // unary minus is called
m.show();
m-m; //binary minus is called
m.show();
return 0;
}
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 22
Output

enter number 25
number is 25 // entered number
number is -25 // negated number
number is 0 // result of 25-25

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 23


Exercise to do
 Write a C++ program to add two objects
of TIME class (hrs,mins and secs) using
1. Add function as member function
2. Friend Function
3. Overloading binary + operator

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 24


Overloading insertion (>>) and extraction
operator (<<)
 Input and output operations are defined in
stream classes.
 istream class contains code for taking
input from input device
 ostream class contains code to give output
to output device
 iostream class is derived from both
instream and outstream class.

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 25


Steps to input user defined object
using>>
 one object of istream class is required.
 Operator >> is redefined
 Definition will take istream object and user
defined object and returns back istream
object
 Function body contains instructions to
input all members of the object

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 26


#include"iostream.h"
#include"conio.h"
class phone_no{
char ar_code[4],exchng[4],number[6];
public:
friend istream& operator >>(istream&, phone_no&);
friend ostream& operator <<(ostream&, phone_no&);
};
istream& operator >>(istream& input ,phone_no& p)
{
input>>p.ar_code>>p.exchng>>p.number;
return(input);
}

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 27


ostream& operator <<(ostream& output, phone_no& p)
{
output<<"ENTERED PHONE NUMBER IS ";
output<<“(“<<p.ar_code<<“)”<<"-”<<p.exchng<<“-” << p.number ;
return output;
}
int main (void)
{
phone_no p1,p2;
clrscr();
cout<<"enter 1st phone number";
cin>>p1;
cout<<"enter 2nd phone number";
cin>>p2;
cout<<p1<<endl<<p2;// firstly << is called for p1 then returned
istream object will call<< for p2
return 0; }

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 28


OUTPUT
enter 1st phone number 010
222
54216
enter 2nd phone number 020
333
54871
ENTERED PHONE NUMBER IS
(010)-222-54216
ENTERED PHONE NUMBER IS
(020)-333-54871

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 29


Operator function as member function
#include"iostream.h"
#include"conio.h"
class phone_no
{
char ar_code[4],exchng[4],number[6];
public:
void operator >>(istream& input) //MEMBER FUNCTION
{
input>>ar_code>>exchng>>number;
}
void operator <<(ostream& output) // MEMBER FUNCTION
{
output<<"ENTERED PHONE NUMBER IS "<<endl;
output<<'('<<ar_code<<')'<<'-'<<exchng<<'-'<<number;
} };
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 30
int main (void)
{
phone_no p1,p2;
cout<<"enter 1st phone number";
cin >> p1;
cout<<"enter 2nd phone number";
cin>> p2;
cout << p1;
cout<<endl;
cout << p2;
// << cant be cascaded here as no value is
returned
return 0; }

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 31


OUTPUT
enter 1st phone number055
666
65984
enter 2nd phone number044
777
36541
ENTERED PHONE NUMBER IS (055)-666-65984
ENTERED PHONE NUMBER IS (044)-777-36541

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 32


Type Conversions

 Basic ---- Class type


(Say int - Class )
 Class type ----- Basic type
( Say Class c1- int)
 One class type --Another class type
(Say class C1--Class c2)

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 33


Basic type to Class type
 Done by using constructors,
 Constructors contain coding to convert
basic data types to make a class variable
(OBJECT)
 E.g complex c1(2,3); may be a call to the
constructor which assign 2 to real part and
3 to imaginary part of the complex variable
c1.

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 34


Class to basic type
 Using data members of object ,any
information of basic data type can be
obtained.
 Say a class employee (id, name, DA,
days) exists then salary for a month can
be computed as product of DA and days.
 An operator can be overloaded with return
type as basic data type , then such
operator can be called for any object of
employee.

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 35


One class to another class type
 Using copy constructors
class1( class2& o),
{ m.data =o.data) // m is created object of class1
 Using operator overloading
Say assignment operator “=” can be defined to do
the required assignments.
 Class1 operator =(class2 o) is defined for class1
{ m.data=o.data }

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 36


Type Conversions int getcode() { return code;}
#include"iostream.h" int getitems() { return items;}
#include"conio.h" float getprice() {return price;}
Class invent2; operator float() { return
class invent1 (items*price); }
{ };
int code,item; float price;
public: class invent2
invent1(int a, int b, float c) { int code;
{ code =a; items=b; price =c;} float value;
void putdata() public: invent2()
{ { code=0;value=0;}
cout<<“Code :”<<code<<“\n”; invent2(int x, float y)
cout<<“Items :”<<items<<“\n”; { code=x; value =y;}
cout<<“Value :”<<price<<“\n”; void putdata()
{ cout<<“Code:”<<code;
} cout<<“Value:”<<value;}

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 37


invent2(invent1 p)
{ code = p.getcode();
vaue = p.getitems()* p.getprice();
}};

int main()
{ invent1 s1(100,5,140.0);
invent2 d1;
float total_value;
total_value=s1; /invent1 to float/
d1=s1 ; / invent1 to invent2 /
cout<<“Product details 1”;
s1.putdata();
cout<<“Stock value”<<total_value;
cout<<“Product details 2”;
d1.putdata();
return 0;
}

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 38


What operators can be overloaded?
+ Unary Plus
-= Assignment by
+ Addition (Sum) Subtraction
++ Prefix Increment * Multiplication (Product)
++ Postfix Increment *= Assignment by
+= Assignment by Addition Multiplication

- Unary Minus (Negation) / Division (Quotient)

- Subtraction (Difference) /= Assignment by Division

-- Prefix Decrement % Modulus (Remainder)


-- Postfix Decrement %= Assignment by Modulus

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 39


<< Bitwise Left Shift
< Less Than
<<= Assignment by Bitwise
Left Shift <= Less Than or Equal To
>> Bitwise Right Shift

>>= Assignment by Bitwise > Greater Than


Right Shift
>= Greater Than or Equal To
~ Bitwise One's Complement

& Bitwise AND != Not Equal To

&= Assignment by Bitwise AND == Equal To


| Bitwise OR
! Logical Negation
|= Assignment by Bitwise OR
&& Logical AND
^ Bitwise XOR

^= Assignment by Bitwise XOR


|| Logical OR

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 40


(type) Cast = Basic Assignment

, Comma () Function Call

sizeof Size-of [ ] Array Subscript


typeid Type Identification * Indirection (Dereference)
new Allocate Storage & Address-of (Reference)
new Allocate Storage
-> Member by Pointer
(Array)
delete Deallocate Storage
->* Member by Pointer
Indirection
delete Deallocate Storage
(Array)

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 41


Exercise to do
 Try to overload new and delete operators
to allocate and to free memory for an
object.
 Define a class string (char array, length)
1. Overload + operator to concatenate two
strings.
2. Overload <= to check which string is
larger.
3. Using constructor copy one string object
to other.

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 42


Questions
A. Which of the following operators can be
overloaded?
1. Less than or equal to(<=)
2. Shorthand operator(+=)
3. Scope resolution operator(::)
4. Unary Increment operator (++)
5. All of the above.

ANS 1,2,4
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 43
B. While defining an overloaded operator
1. Operator keyword must be included in
function definition
2. Any number and type of arguments can
be passes to the operator function
3. Operator can perform any function.
4. At least one of the arguments must be of
user defined data type.

ANS 1,3 and 4


OOPS (Unit - 2) Seema Chandna ( Department of IT ) 44
C. Overloading an operator can
 1. change its existing meaning
 2. be used to give additional meaning to
the existing operator.
 3.provide more than two meanings to an
operator (depending on number of args)
 4.be done for dot operator
 5. none is true.

ANS 2,3
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 45
D. Which is (are) false about operator
function?
1.Can be defined only as a member function
2.Can return only objects of built in data
types
3.Can be defined outside the class
4.Can take any type of arguments
5. Always takes one argument less than
required for that operator.

ANS 3 and 4
OOPS (Unit - 2) Seema Chandna ( Department of IT ) 46
E. Which of the following can be overloaded
using friend function?
1. Assignment (=)
2. Unary minus(-) and subscript([])
3. Dot operator (.)
4. <= and ++
5. Scope resolution operator(:: )

ANS only 4

OOPS (Unit - 2) Seema Chandna ( Department of IT ) 47

You might also like