You are on page 1of 11

Operator Overloading

What is Operator overloading?


In C++, it's possible to change the way operator works.
Operator Overloading means providing multiple definition for the
same operator.
Operator overloading provides a simple and easy way for the development
of new definitions for most of the operators in C++.
The meaning of an operator is always same for variable of basic types like:
int, float, double etc.
For example: To add two integers, + operator is used.
However, for user-defined types (like: objects), you can redefine the way
operator works.
This feature in C++ programming that allows programmer to redefine the
meaning of an operator (when they operate on class objects) is known as operator
overloading.
We can overload all the operators in C++ except the following:
1. Scope operator (::)
2. Size operator (Sizeof)
3. member selector(.)
4. member pointer selector(*)
5. ternary operator(?:)
Why Operator overloading is needed in C++?
Consider the following two programs
1 2
int main() int main()
{ {
int a = 10, b = 20, c; classnname obj1(10,20), obj2(20,30),
c = a + b; Obj3;
} Obj3 = Obj1 + Obj2;
// This will run normally }// This will give us an error
The code in the block 2 will give us error at compile-time itself because the
compiler does not know how to add two objects.
It cannot understand that to obtain values for obj3 it has to add
corresponding values obj1 and obj2.
To solve this problem, we have to use concept of Operator overloading.
How to overload operators in C++ programming?
To overload an operator, a special operator function is defined inside the class as:
class className  Here, returnType is the return
{ type of the function.
... .. ...
 The returnType of the function is
public
followed by operator keyword.
returnType operator symbol (arguments)
{  symbol is the operator symbol you
... .. ... want to overload. Like: +, <, -, ++
}
 You can pass arguments to the
... .. ...
operator function in similar way as
};
functions.
53
Operator Overloading
6.1 Overloading unary operators
Operators that only operate on one operand are known as unary operators.
Example:
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.
Thus, it is an overloading of an operator, which is operating on a single
operand.
In unary operator function, no arguments should be passed.
It works only with one class objects.
/*Program to demonstrate Overloading unary operators*/
Example 1:
#include<iostream>
#include<conio.h>
class IncreDecre
{
int a, b;
public:
void accept()
{ cout<<"\n Enter Two Numbers : \n";
cout<<" ";
cin>>a;
cout<<" ";
cin>>b;
}
void operator--() //Overload Unary Decrement
{ a--;
b--;
}
void operator++() //Overload Unary Increment
{ a++;
b++;
}
void display()
{ cout<<"\n\n A : "<<a;
cout<<"\n B : "<<b;
}
};
int main()
{
IncreDecre id;
clrscr()
id.accept();
--id;
cout<<"\n After Decrementing : ";
id.display();
++id;
cout<<"\n\n After Incrementing : ";
id.display();
getch();
return 0;
}
54
Operator Overloading

Example 2:
#include<iostream.h>
#include<conio.h>
class complex
{
int a, b, c; //Data Members
public:
void getvalue()
{ cout << "Enter the Real and Complex part of Numbers:";
cin >> a>>b;
}
void operator++()
{ a = ++a;
b = b;
}
void operator--()
{ a = --a;
b = b;
}
void display()
{ cout << a << "+\t" << b << "i" << endl;
}
};
int main()
{
clrscr();
complex obj;
obj.getvalue();
++obj;
cout << " Overloading Increment operator on Complex Number\n";
obj.display();
--obj;
cout << " Overloading Decrement operator Complex Number\n";
obj.display();
getch();
return 0;
}
The unary operators that can be overloaded are the following:
1) ! (logical NOT)
2) & (address-of)
3) ~ (one's complement)
4) (pointer dereference)
5) + (unary plus)
6) - (unary negation)
7) ++ (increment)
8) -- (decrement)

55
Operator Overloading
6.2 Overloading binary operators:
As the name suggests, those operators which operate on two operands or
data are called binary operators.
6.2.1 Overloading arithmetic operators:
addition (+) operator, subtraction (-) operator, division (/) operator etc. are
all example of arithmetic operators.
We can overload these operators to work with objects as per our need.
Syntax:
return_type operator arithmetic_operator_symbol(parameters)
{
// function definition
}
/*Program to demonstrate Overloading arithmetic operators*/
#include<iostream.h>
#include<conio.h>
class Complex
{
int real, imaginary;
public:
void accept()
{ cout<<"\n Enter a Complex Number : ";
cin>>real>>imaginary;
}
//returnType operator symbol (arguments)  Syntax
Complex operator + (Complex obj) //Overloading '+' operator
{
Complex c;
c.real = real+obj.real;
c.imaginary = imaginary+obj.imaginary;
return(c);
}
void display()
{ cout<<real<<"+"<<imaginary<<"i"<<"\n";
}
};
int main()
{
Complex c1, c2, sum; //Created Object of Class Complex i.e c1 and c2
c1.accept(); //Accepting the values
c2.accept();
sum = c1+c2; //Addition of object
cout<<"\n Entered Values : \n\t";
c1.display(); //Displaying user input values
cout<<"\t";
c2.display();
cout<<"\n Addition of Real and Imaginary Numbers: \n\t";
sum.display(); //Displaying the addition
getch();
return 0;
}
56
Operator Overloading
6.2.2 Overloading relational operators
There are various relational operators supported by C++ language like (<,
>, <=, >=, ==, etc.) which can be used to compare C++ built-in data types. You
can overload any of these operators, which can be used to compare the objects of
a class.
Syntax:
return_type::operator relational_operator_symbol(parameters)
{
// function definition
}
/*Program to demonstrate Overloading relational operators*/
#include<iostream.h>
#include<conio.h>
class Greater
{
int a;
public:
void getdata()
{ cout<<"\n\n Enter a number: ";
cin>>a;
}
void display()
{
cout<<a;
}
Greater operator > (Greater o2)
{
Greater o3;
if (a>o2.a)
{
o3.a = a;
}
else
{ o3.a = o2.a;
}
return(o3);
}
};
int main()
{
clrscr();
Greater o1, o2, o3;
o1.getdata();
o2.getdata();
o3=o1>o2;
cout<<"\nGreatest of two numbers is:";
o3.display();
getch();
return 0;
}

57
Similarly, we can overload other relation operators.
Operator Overloading
6.2.3 Concatenate strings using operator overloading:
Given two strings, the goal is to concatenate (combine) the two strings using
Operator Overloading in C++ to obtain a single string.

Approach 1 : Using unary operator overloading.


1. To concatenate two strings using unary operator overloading. Declare a
class with two string variables.
2. Create an instance of the class and call the Parametrized constructor of the
class to initialize those two string variables with the input strings from the
main function.
3. Overload the unary operator to concatenate these two string variables for
an instance of the class.
4. Finally, call the operator function and concatenate two class variables.

Approach 2 : Using binary operator overloading.


1. Declare a class with a string variable and an operator function ‘+’ that
accepts an instance of the class and concatenates it’s variable with the
string variable of the current instance.
2. Create two instances of the class and initialize their class variables with the
two input strings respectively.
3. Now, use the overloaded operator (+) function to concatenate the class
variable of the two instances.

/*Program to demonstrate Concatenate strings using operator


overloading */
// The following program implements approach 2 mentioned above
#include<iostream.h>
#include<string.h>
#include<conio.h>
class String
{
char str[20];
public:
void input()
{
cout<<" Enter a String : ";
cin>>str;
}
void display ()
{
cout<<str;
}
String operator + (String x) //Concatenating String
{
String s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
};

58
Operator Overloading
int main()
{
String str1, str2, str3;

str1.input();
str2.input();

cout<<"\n You Entered First String as : ";


str1.display(); //Displaying First String

cout<<"\n You Entered Second String as : ";


str2.display(); //Displaying Second String

str3=str1+str2; //String is concatenated. Overloaded '+' operator


cout<<"\n\n Concatenation of Strings is : ";
str3.display();

getch();
return 0;
}

6.2.4 Comparison of strings using operator overloading.


Given two strings, the goal is to check if the two strings are equal or not,
using Operator Overloading.
The strings are compared lexicographically, that is comparison is done
character by character starting from the first character until the characters in
both strings are equal or a NULL character is encountered.

Approach: Using binary operator overloading.


1) Declare a class with a string variable and operator function ‘==’, ‘<=' and
'>=’ that accepts an instance of the class and compares its variable with the
string variable of the current instance.
2) Create two instances of the class and initialize their class variables with the
two input strings respectively.
3) Now, use the overloaded operator (==, <= and >=) function to compare the
class variable of the two instances.

59
Operator Overloading
/* Program to demonstrate Comparison of strings using operator
overloading */
#include<iostream>
#include<string.h>
#include<conio.h>
class Compare
{
public:
char str[20];
public:
void get_string()
{
cout<<" Enter a String : ";
cin>>str;
}
void display()
{
cout<<str;
}
int operator == (Compare st) //Comparing String
{
if( strcmp ( str , st.str ) == 0 )
return 1;
else
return 0;
}
};
int main()
{
Compare str1, str2;
clrscr();
str1.get_string();
str2.get_string();
cout<<"\n First String is : ";
str1.display(); //Displaying First String

cout<<"\n Second String is : ";


str2.display(); //Displaying Second String

if (str1 == str2) //Comparing two strings. Overloaded '==' operator


{
cout<<"\n\n Both Strings are Equal\n";
}
else
{
cout<<"\n\n Both Strings are Not Equal\n";
}
getcg();
return 0;
}

60
Operator Overloading
6.3 Overloading with and without friend function
Operator overloading can be achieved in two ways -
1) By an operator overloading by member function
2) By an operator overloading non-member friend function.

6.3.1 Overloading without friend function


When the overloading of an operator in C++ is done using the member
function it is known as Overloading without friend function.

(All the above examples that we have studied so far are ‘Overloading
without friend function’ write any one example if asked in exam.)

6.3.1 Overloading using friend function


In this approach, the operator overloading function must precede with
friend keyword, and declare a function class scope.
Friend operator function takes two parameters in a binary operator, varies
one parameter in a unary operator. All the working and implementation would
same as binary operator function except this function will be implemented outside
of the class scope.
/* Program to demonstrate Overloading using friend function */
#include<iostream.h>
#include<conio.h>

class Complex
{
int num1, num2;
public:
void accept()
{
cout<<"\n Enter Two Complex Numbers : ";
cin>>num1>>num2;
}

//Overloading '+' operator using Friend function


friend Complex operator+(Complex c1, Complex c2);

void display()
{
cout<<num1<<"+"<<num2<<"i"<<"\n";
}
};

Complex operator+(Complex c1, Complex c2) // Friend Function


{
Complex c;
c.num1=c1.num1+c2.num1;
c.num2=c1.num2+c2.num2;
return(c);
}

61
Operator Overloading

int main()
{
Complex c1,c2, sum; //Created Object of Class Complex i.e c1 and c2
clrscr();

c1.accept(); //Accepting the values


c2.accept();

sum = c1+c2; //Addition of object

cout<<"\n Entered Values : \n\t";


c1.display(); //Displaying user input values
cout<<"\t";
c2.display();

cout<<"\n Addition of Real and Imaginary Numbers : \t";


sum.display();

getch();
return 0;
}

Output:

62
Operator Overloading

6.4 Rules for operator overloading:


In C++, following are the general rules for operator overloading.
1) Only built-in operators can be overloaded. New operators cannot be
created.
2) Arity (i.e. the number of arguments that it can take) of the operators cannot be
changed.
3) Precedence and associativity of the operators cannot be changed.
4) Overloaded operators cannot have default arguments except the function
call operator () which can have default arguments.
5) Operators cannot be overloaded for built in types only. At least one operand
must be used defined type.
6) We do not use a friend function to overload certain operators. However, the
member functions can be used to overload those operators.
7) When unary operators are overloaded through a member function, they
take no explicit arguments, but, if they are overloaded by a friend function,
they take one argument.
8) When binary operators are overloaded through a member function, they
take one explicit argument, and if they are overloaded through a friend
function, they take two explicit arguments.

63

You might also like