21CSC101T
Object Oriented Design and Programming
POLYMORPHISM – Operator Overloading
Operator Overloading
• The mechanism of giving special meaning to a operator is called
operator overloading.
• It gives flexible option for the creation of new definitions for most of
the C++ operators.
2
Operator Overloading
• Operator overloading
• Enabling C++’s operators to work with class objects
• Using traditional operators with user-defined objects
• Requires great care; when overloading is misused, program difficult to
understand
3
Operator Overloading:
▪ Operator – It is a symbol that indicates an operation.
▪ Arithmetic operators are + (add two numbers), - (subtract two numbers), * (
Multiply two numbers), / ( Divide between two numbers).
▪ At now, we will take an Addition ‘+’ Sign, its use of ‘+’ sign is
5+5=10
2.5+2.5=5
❖ For Example, ‘+’ operator can be overloaded to perform an operation of string
concatenation along with its pre-defined job of adding two numeric values.
❖ When an operator is overloaded, none of its original meaning will be lost.
❖ After overloading the appropriate operators, you can use C++’s built in data
types.
Types of Operator Overloading
• Operator Overloading can be done by using three approaches, they are
1. Overloading unary operator. https://www.youtube.com/watch?v=jcn70G4YhPw
2. Overloading binary operator. https://www.youtube.com/watch?v=7QVvV-dkyvE
3. Overloading binary operator using a friend function.
Types of Operators
Unary Operator
- Operators attached to a single operand.
• (-a, +a, --a, ++a, a--, a++)
Binary Operator
- Operators attached to two operands.
• (a-b, a+b, a*b, a/b, a%b, a>b, a<b )
Operator Overloading
• With operator overloading, you can redefine the way an operator works only for the
user-defined types (objects, structures).
• You cannot use it for built-in types (float, char, int, etc.).
• The = and & C++ operators are overloaded by default.
• For example, you can copy the objects of the same Class directly using the =
operator.
Restrictions on Operator Overloading
Following C++ Operator can’t be overloaded
• :: - Scope resolution operator
• ?: - ternary operator/conditional operator
• . - member selector
• * - member pointer selector
• sizeof operator
10
Overloadable Operators
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
Non-overloadable Operators
:: .* . ?: sizeof
Restrictions on Operator Overloading
• Overloading restrictions
• Precedence , Associativity, Arity (number of operands) of an operator cannot be
changed
• No new operators can be created
• Use only existing operators
• No overloading operators for built-in types
• Cannot change how two integers are added
12
General Rules for Operator Overloading
• Overloading an operator - Write function definition as normal
Syntax:
returntype classname::operator op(argument list)
{
Function body // Task Defined
}
• Return type is the type of the value returned by the specified operation
• op is the operator being overloaded
• operator is the keyword
• operator op is the function name.
• Function name is keyword operator followed by the symbol for the operator being overloaded
13
General Rules for Operator Overloading
• Using operators
• To use an operator on a class object it must be overloaded unless the
assignment operator(=)or the address operator(&)
• Assignment operator(=) by default performs memberwise assignment
• Address operator (&) by default returns the address of an object
Steps
1. Create a class that is to be used
2. Declare the operator function in the public part of the class. It may be either
member function or friend function.
3. Define operator function to implement the operation required
4. Overloaded can be invoked using the syntax such as: op x;
#include <iostream>
using namespace std; int main()
class TestClass {
{
TestClass tc;
private:
int count; --tc;
public: tc.Display();
TestClass() return 0;
{ count = 5; }
}
void operator --()
{
Output:
count = count - 3;
}
void Display()
{
cout << "Count: " << count;
}
};
One of the exciting features of C++
Works only on the single variable
It can be overloaded two ways
1. Static member function
2. Friend function
-,+,++,-- those are unary operator which we can overloaded.
Using a member function to Overload Unary Operator
Using a Friend Function to Overload a Unary Operator
• The function will take one operand as an argument.
• This operand will be an object of the class.
• The function will use the private members of the class only with the object name.
• The function may take the object by using value or by reference.
• The function may or may not return any value.
• The friend function does not have access to the this pointer.
#include<iostream>
using namespace std; int main()
class demo {
{ demo obj1;
int x,y,z; obj1.getdata(10,20,30);
public: obj1.display();
void getdata (int a, int b,int c) -obj1;
{ obj1.display();
x=a; return 0;
y=b; }
z=c;
}
void display() Output:
{ x=10
cout<<"x="<<x<<"\ny="<<y<<"\nz="<<z<<endl; y=20
} z=30
void operator -() x=-10
{ y=-20
x=-x;
z=-30
y=-y;
z=-z;
}
};
In Binary operator overloading function, there should be one argument to be
passed.
It is overloading of an operator operating on two operands.
void operator *(multiply c)
#include<iostream> {
class multiply multiply temp;
{ temp.first=first*c.first;
int first,second; temp.second=second*c.second;
public: return temp;
}
void getdata(int a,int b)
};
Output:
{ 45
int main()
first=a; 900
{
second=b; multiply obj1,obj2,obj3;
} obj1.getdata(15,20);
void display() obj2.getdata(3,45);
{ obj3=obj1*obj2;
obj3.display();
cout<<“first=“<<first<<“second=“<<second<<endl;
return 0;
}
}
#include<iostream>
using namespace std; void print()
class Complex {
{ cout << real << " + i" << imag << endl;
private:
int real, imag; }
public: };
Complex(int r = 0, int i =0) int main()
{
{
real = r;
imag = i;
Complex c1(10, 5), c2(2, 4);
} Complex c3 = c1 + c2; // An example call to
// This is automatically called when '+' is used with between "operator+"
two Complex objects c3.print();
Complex operator + (Complex o) }
{
Complex res;
res.real = real + o.real;
res.imag = imag + o.imag;
return res; Output:
} 12 + i9
Overloading the assignment operator
• The assignment operator (operator=) is used to copy values from one object to another already existing
object.
Assignment vs Copy constructor
• The purpose of the copy constructor and the assignment operator are almost equivalent -- both copy
one object to another. However, the copy constructor initializes new objects, whereas the assignment
operator replaces the contents of existing objects.
• The difference between the copy constructor and the assignment operator causes a lot of confusion for
new programmers, but it’s really not all that difficult. Summarizing:
• If a new object has to be created before the copying can occur, the copy constructor is used (note: this
includes passing or returning objects by value).
• If a new object does not have to be created before the copying can occur, the assignment operator is
used.
#include <iostream> int main()
using namespace std;
{
class Distance
{ Distance D1(11, 10), D2(5, 11);
private: cout << "First Distance : ";
int feet; D1.displayDistance();
int inches; cout << "Second Distance :";
public: // required constructors
D2.displayDistance();
Distance()
{ // use assignment operator
feet = 0; inches = 0; D1 = D2;
} cout << "First Distance :";
Distance(int f, int i) D1.displayDistance();
{
return 0;
feet = f;
inches = i; }
}
void operator = (Distance D ) Output:
{ First Distance : F: 11 I:10
feet = D.feet;
inches = D.inches; } Second Distance :F: 5 I:11
// method to display distance First Distance :F: 5 I:11
void displayDistance()
{
cout << "F: " << feet << " I:“ << inches << endl;
}
};