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

Operator Overloading Operator Overloading Operator Overloading Operator Overloading

The document discusses operator overloading in C++, which allows operators to work with user-defined types like classes in the same way they work with built-in types. Operator overloading is implemented by defining member or friend functions that specify the behavior of operators when used with class objects. This allows classes to define behaviors for operators like +, -, *, / and others in a polymorphic way and extend the meaning and usage of operators to user-defined types.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Operator Overloading Operator Overloading Operator Overloading Operator Overloading

The document discusses operator overloading in C++, which allows operators to work with user-defined types like classes in the same way they work with built-in types. Operator overloading is implemented by defining member or friend functions that specify the behavior of operators when used with class objects. This allows classes to define behaviors for operators like +, -, *, / and others in a polymorphic way and extend the meaning and usage of operators to user-defined types.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Operator Overloading

©Somya Khanna(OOPS-2011) 1
Operator Overloading is used
•To make the user defined data types behave in a manner similar to
the built-in data type.
•Allowing the user to redefine the language.
•Provides the additional meaning to operators.
•Method of realizing polymorphism(multiple actions)

Principle Areas of concern:-


•Extending capability of operators to operate on user defined data.
•Data conversion.
•Extends the semantics of an operator without changing its syntax.

complex c3,c1,c2; //c1,c2,c3 belong to user defined data types.


c3=addcomplex(c1,c2);
` or
c3=c1+c2; //operator overloading

Operators are classified as Unary and Binary. Almost all operators are
overloaded, but at least one operand must be an instance of a class
object.
©Somya Khanna(OOPS-2011) 2
Allows almost all operators except
– Member access (dot operator)
– Scope resolution (::)
– Conditional(?:)
– Pointer to member(.*)
– Size of Datatype (sizeof(…))
keyword operator being overloaded
Syntax:
returntype classname::operator op(arglist)
{
//functions body
} function name
Or
returntype operator op(arglist)
{ //function body }

Note: When operator is overloaded its original meaning is not lost.


operator + which is overloaded to add two class object can still be used
to add two integers.

©Somya Khanna(OOPS-2011) 3
Function name must be a non-static member function or friend function.

A friend function will have one argument for unary operator and two
arguments for binary operators.
friend vector operator+(vector, vector);
friend vector operator-(vector);
friend int operator==(vector, vector);

 A Member function will have no arguments for unary operators and


one argument for binary operators.

vector operator+(vector);
vector operator-();
vector operator-(vector &a);
int operator==(vector);

©Somya Khanna(OOPS-2011) 4
Unary Operator: Using Non-static Member Function
#include<iostream.h>
void addition::display()
#include<conio.h>
{
class addition
cout<<"\nValues of a
{ int a; int b; int c;
:"<<a<<"\nValues of b :"<<b;
public:
cout<<"\nThe addition is
void getdata();
:"<<c;
void display();
}
void operator +(); //overloaded unary plus
};
void main()
{
void addition::operator+()
addition a1;
{ c=a+b; }
clrscr();
a1.getdata();
void addition::getdata()
+a1; //activates operator+
{
function
cout<<"\nEnter the values of a and b: ";
a1.display();
cout<<"\na :";
getch();
cin>>a;
}
cout<<"b :";
cin>>b; }
©Somya Khanna(OOPS-2011) 5
Unary Operator: Using friend Function
#include<iostream.h> void addition::display()
#include<conio.h> {
class addition cout<<"\nValues of a :"<<a;
{ int a; }
public:
void getdata(); void main()
void display(); {
friend void operator +(addition &b); addition a1;
//overloaded unary plus, argument clrscr();
passed by reference }; a1.getdata();
a1.display();
void operator+(addition &b) +a1; //activates friend +function
{ b.a=b.a+1; } a1.display();
getch();
void addition::getdata() }
{ Note: Argument is passed by
cout<<"\nEnter the values : "; reference. If argument is passed by
cout<<"\na :"; value, then only a copy is passed
cin>>a; when operator function is
} activated.
©Somya Khanna(OOPS-2011) 6
Only Some Unary Operators can be overloaded like:
+
-
!
~
++
--

©Somya Khanna(OOPS-2011) 7
Unary Minus

#include<iostream.h>
void sub::display()
#include<conio.h>
{
class sub
cout<<"\nValues of a :"<<a;
{
}
int a;
public:
void main()
void getdata();
{
void display();
sub a1;
void operator -(); //overloaded
clrscr();
unary minus
a1.getdata();
};
-a1;
void sub::operator-()
a1.display();
{ a=-a; }
getch();
}
void sub::getdata()
{ cout<<"\nEnter the value ofa: ";
OUTPUT
cout<<"\na :";
cin>>a;
Enter the value ofa:
}
a :57
Values of a :-57
©Somya Khanna(OOPS-2011) 8
Unary Minus- With Friend Function

#include<iostream.h>
void sub::display()
#include<conio.h>
{
class sub
cout<<"\nValues of a :"<<a;
{ int a;
}
public:
void main()
void getdata();
{
void display();
sub a1;
friend void operator -(sub &b);
clrscr();
//overloaded unary minus,
a1.getdata();
argument passed by reference
a1.display();
};
-a1;
a1.display();
void operator-(sub &b)
getch();
{ b.a = -b.a; }
}
void sub::getdata()
OUTPUT
{
cout<<"\nEnter the values : ";
Enter the values :
cout<<"\na :";
a :65
cin>>a;
Values of a :65
}
Values of a©Somya
:-65 Khanna(OOPS-2011) 9
Increment and Decrement Operator Overloading
#include<iostream.h>
class increment id3=id1++; //returned object of id1 is
{ assinged to id3
int value; id4=++id2; //returned object of id2 is
public: assinged to id4
increment() cout<<"\nNew Value of id1
{ value=0; } :"<<id1.getdata();
int getdata() cout<<"\nNew Value of id2
{ return value; } :"<<id2.getdata();
cout<<"\nNew Value of id3
increment operator ++() :"<<id3.getdata();
{ cout<<"\nNew Value of id4
increment temp; :"<<id4.getdata();
value=value+1; }
temp.value=value; OUTPUT
return temp;
}}; Value of id1 :0
void main() Value of id2 :0
{ New Value of id1 :1
increment id1,id2,id3,id4; New Value of id2 :1
cout<<"\nValue of id1 :"<<id1.getdata(); New Value of id3 :1
cout<<"\nValue of id2 :"<<id2.getdata(); New Value
©Somyaof id4 :1
Khanna(OOPS-2011) 10
Nameless Temporary Objects
#include<iostream.h>
id3=id1++; //returned object
class increment
of id1 is assigned to id3
{ int value;
id4=++id2; //returned object
public:
of id2 is assinged to id4
increment()
cout<<"\nNew Value of id1
{ value=0; }
:"<<id1.getdata();
increment (int val) //parametrized
cout<<"\nNew Value of id2
constructor
:"<<id2.getdata();
{ value=val; }
cout<<"\nNew Value of id3
int getdata()
:"<<id3.getdata();
{ return value; }
cout<<"\nNew Value of id4
increment operator ++()
:"<<id4.getdata();
{ //creates a nameless object by passing
an intialization value.
getch();
value=value+1;
}
return increment(value); } };
OUTPUT
void main()
Value of id1 :0
{
Value of id2 :0
increment id1,id2,id3,id4;
New Value of id1 :1
clrscr();
New Value of id2 :1
cout<<"\nValue of id1 :"<<id1.getdata();
New Value of id3 :1
cout<<"\nValue of id2 :"<<id2.getdata();
New©Somya
Value Khanna(OOPS-2011)
of id4 :1 11
Limitation of Increment and Decrement Operator

When ++ and – operators are overloaded, there is no distinction


between prefix and postfix overloaded operator function.

id3=id1++;
id4=++id2;
Gave the same result.

In order to distinguish between them, a new syntax for postfix


overloaded function is used:-

operator ++(int);

©Somya Khanna(OOPS-2011) 12
Overloaded Postfix and Prefix Operator
#include<iostream.h>
void main()
{
class increment
increment id1,id2,id3,id4;
{ int value;
cout<<"\nid1 :"<<id1.getdata();
public:
cout<<"\nid2 :"<<id2.getdata();
increment()
id3=id1++; //returned object of id1 is
{ value=0; }
assinged to id3
increment (int val) //parametrized
id4=++id2; //returned object of id2 is
constructor
assinged to id4
{ value=val; }
cout<<"\nNew id1 :"<<id1.getdata();
int getdata()
cout<<"\nNew id2 :"<<id2.getdata();
{ return value; }
cout<<"\nNew id3 :"<<id3.getdata();
increment operator ++() //prefix
cout<<"\nNew id4 :"<<id4.getdata();
operator
}
{ //creates a nameless object by passing
OUTPUT
an initialization value.
Value of id1 :0
return increment(++value); }
Value of id2 :0
increment operator ++(int)//postfix
New Value of id1 :1
operator
New Value of id2 :1
{ return increment(value++); }
New Value of id3 :0
};
New Value of id4 :1
©Somya Khanna(OOPS-2011) 13
List of Binary Operators

, Comma < Less than


!= Inequality << Left shift
% Modulus <<= Left shift assignment
%= Modulus assignment <= Less than or equal to
& Bitwise AND = Assignment
&& Logical AND == Equality
&= Bitwise AND assignment > Greater than
* Multiplication >= Greater than or equal to
*= Multiplication assignment >> Right shift
+ Addition >>= Right shift assignment
+= Addition assignment ^ Exclusive OR
– Subtraction ^= Exclusive OR assignment
–= Subtraction assignment | Bitwise inclusive OR
–> Member selection |= Bitwise inclusive OR
–>* Pointer-to-member assignment
selection || Logical OR
/ Division
/= Division assignment
©Somya Khanna(OOPS-2011) 14
Binary Operator Overloading

returntype operator operatorsymbol(arg)


{
//body of function
}

Binary operator function takes the first object as an implicit operand


and the second operand must be passed explicitly.

The data member of first object is accessed without using dot


operator and data member of second argument is accessed using dot
operator ,if that argument is an object.

©Somya Khanna(OOPS-2011) 15
Arithmetic Operator Overloading
#include<iostream.h> void complex::getdata()
class complex { cout<<"\nEnter the values :";
{ float real; cout<<"\nReal Part :";
float imag; cin>>real;
public: cout<<"\nImaginary Part :";
complex() cin>>imag; }
{ real=imag=0.0; }
complex operator+(complex c1); void complex::display()
void getdata(); { cout<<"\nReal Part :"<<real;
void display(); cout<<"\nImaginary Part :"<<imag;
}; }

complex complex ::operator+(complex c1)


{ void main()
complex temp; {
temp.real=real+c1.real; complex c2,c3,c4;
temp.imag=imag+c1.imag; c2.getdata();
return (temp); c3.getdata();
} c4=c2+c3;
c4.display();
}
©Somya Khanna(OOPS-2011) 16
Comparison Operator
#include<iostream.h> void main()
#include<conio.h> {
enum bool {FALSE,TRUE}; com c2=20;
class com com c3=12;
{ int value; clrscr();
public:
com() cout<<"\nValue is of c2:"<<c2.getvalue();
{ value=0; } cout<<"\nValue is of c3:"<<c3.getvalue();

com(int val) if(c2<c3)


{ value=val; } cout<<"\n"<<c2.getvalue()<<" is smaller.";
else
int getvalue() cout<<"\n"<<c3.getvalue()<<" is smaller.";
{ return value; } getch();
}
bool operator <(com c1)
{ OUTPUT
return
(value<c1.value?TRUE:FALSE); } Value is of c2 : 20
}; Value is of c3 : 12
12 is smaller.
©Somya Khanna(OOPS-2011) 17
Operator Overloading using Friend Function
#include<iostream.h> void main()
#include<conio.h> {
class add add a2=20,a3=10;
{ add a4;
int a; clrscr();
public: cout<<"\n a2 :"<<a2.getvalue();
add() {a=0; } cout<<"\n a3 :"<<a3.getvalue();
add(int value) a4=a2 + a3;
{ a=value; } cout<<"\nThe Result is :"<<a4.getvalue();
int getvalue() getch();
{ return a; } }

friend add operator +(add,add); OUTPUT


};
a2 :20
add operator +(add x,add y) a3 :10
{ The Result is :30
add z;
z.a=x.a+y.a;
return (z.a);
}
©Somya Khanna(OOPS-2011) 18
Some Friend Functions that cannot be overloaded :-

= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access operator

©Somya Khanna(OOPS-2011) 19
Data Conversion

Changing a data type of a value is referred to as “


Type Conversion or Casting". There are two ways to do this:
Implicit – the change is implied
Explicit – the change is explicitly done with the cast operator

The value being changed may be:


Promotion – going from a smaller domain to a larger domain
Demotion – going from a larger domain to a smaller domain

Conversion:-
Between Basic Data Types
Between Objects and basic Types
Between Objects of Different Classes

©Somya Khanna(OOPS-2011) 20
Between Basic Types
Implicit Type Conversion:-
Conversion of data without user intervention.
Eg:- char to int, float to double

int a=20;
float b;
b=a;

int a;
char ch=‘A’;
a=ch;

Explicit Type Conversion:-


Conversion of data done by the user.
Eg:- char to int, int to char, float to int

int a=20,c=30,d=65;
float b;
b=(float)a/c;
char ch;
ch=(char)d; ©Somya Khanna(OOPS-2011) 21
Between Objects and Basic Types

a) Basic to User-Defined
Primitive data item
constructor(basictype)
{//steps for converting basic type to object attributes
}

b) User-Defined to Basic
keyword operator Primitive data type

operator basictype()
{//steps for converting object attributes to basictype
}

©Somya Khanna(OOPS-2011) 22
#include<iostream.h> void show()
{ cout<<"\nLength : "<<len; } };
class length
{ float len; void main()
public: {
length() length l1;
{ len=0.0; } float len3;
cout<<"\nEnter the length : ";
length(float len1) //basic to user cin>>len3;
defined l1=len3;
{ len=len1*100.0; } l1.show();

operator float() //user defined to float len4;


basic type length l2;
{ float len2; l2.getdata();
len2=len*100.00; len4=l2;
return (len2); } cout<<"\nLength is : "<<len4;
}
void getdata()
{
cout<<"\nEnter the Value : ";
cin>>len; } ©Somya Khanna(OOPS-2011) 23
Conversion between Objects of Different Classes
Consider:-
objx=objy; //objects of different types

objx is the object of class x and objy is the object of class y.

Conversion takes plcae from class y to class x, so class y is source class


and class x is destination class.

Such conversions are carried out by constructor or a conversion


function(depends on the type conversion function to be located in source
class or destination class).

In Source class :- casting operator


In Destination class :- constructor

©Somya Khanna(OOPS-2011) 24
#include<iostream.h> //invent1 to invent2
class invent2; //destination class /*operator invent2
declared {
class invent1 invent2 temp;
{ int code; temp.code=code;
int items; temp.value=price*items;
float price; return temp;
public: } */
invent1(int a,int b,float c) };
{ code=a;
items=b; class invent2 //destination class
price=c; } { int code;
void putdata() float value;
{ cout<<"\ncode : "<<code; public:
cout<<"\nItems : "<<items; invent2()
cout<<"\nValue : "<<price; } { code=0; value=0; }

int getcode() { return code; } invent2(int x,float y)


int getitems() { return items;} { code=x;
float getprice() { return price; } value=y; }
operator float() {return
(items*price);//invent1 to float} ©Somya Khanna(OOPS-2011) 25
void putdata() cout<<"\nStock value ";
{ cout<<"\ncode : "<<code; cout<<"Value ="<<total_value;
cout<<"\nvalue : "<<value; }
cout<<"\nProduct Details(invent2)";
invent2(invent1 p) //constructor for d1.putdata();
conversion getch();
{ code=p.getcode(); }
value=p.getitems() * p.getprice(); } };

void main() OUTPUT


{ invent1 s1(100,5,140.0);
invent2 d1; Product Details(invent1)
float total_value; code : 100
/*invent1 to float (operator float will be Items : 5
called*/ Value : 140
total_value=s1; Stock value
/*invent1 to invent2 (conversion Value =700
function will be called*/ Product Details(invent2)
d1=s1; code : 100
cout<<"\nProduct Details(invent1)"; value : 700
s1.putdata();
©Somya Khanna(OOPS-2011) 26
Subscript overloading [ ]

•Useful for bound checking while accessing elements of an array.

•Class checks for validity of accesses to array of objects and permit


access to it members only when the index value is valid.

•An array of primitive data type can be accessed using integer


subscript.
•When overloaded, it takes parameters other than integer types.

•Arguments of an operator function [ ] need not be an integer, it can


be any data type.

©Somya Khanna(OOPS-2011) 27
#include<iostream.h> /takes name as input,return account
#include<conio.h> number
#include<string.h> int accountbook::operator[](char
typedef struct accountentry *namein)
{ {for(int i=0;i<acount;i++)
int number; //account number if(strcmp(namein,account[i].name)==0)
char name[25]; //name of account return account[i].number;//found
holder name, return its account number
}accountentry; return 0;
}
class accountbook
{ private: //takes number as input,returns same
int acount; //account holders count corresponding to account number
accountentry account[10]; char *accountbook::operator[](int
//accounts table; numberin)
public: {
accountbook(int acountin) for(int i=0;i<acount;i++)
{acount=acountin; } if(numberin==account[i].number)
void account_entry(); return account[i].name;
int operator[](char *namein); return 0;
char *operator[](int numberin); }; }
©Somya Khanna(OOPS-2011) 28
void accountbook::account_entry() cout<<"\nTo access Name Enter
{ Account Number:";
for(int i=0;i<acount;i++) cin>>accno;
{ cout<<"\nName :
cout<<"\nAccount Number: "; "<<accounts[accno];
cin>>account[i].number; //operator[](int numberin)
cout<<"\nAccount Holder Name: "; cout<<"\nTo access Account
cin>>account[i].name; Number Enter Name:";
}} cin>>name;
cout<<"\nAccount Number :
void main() "<<accounts[name];
{ //operator[](char *namein)
int accno; getch();
char name[25]; }
accountbook accounts(5);//account
having 5 customers
cout<<"\nBuilding 5 Customers
Database";
accounts.account_entry();
//read
cout<<"\nAccessing Accounts
Information"; ©Somya Khanna(OOPS-2011) 29

You might also like