Module - 3
Module - 3
Module - 3
Operator Overloading
Operator Overloading:
• We can overload most operators so that they perform special operations relative to classes that
we create.
• For example, a class that maintains a stack might overload + to perform push operation and –
to perform a pop operation.
• When an operator is overloaded, none of its original meanings are lost. Instead , the type of
objects it can be applied to is expanded
• It is the most powerful feature in c++, it allows the full integration of new class types into the
programming environment.
• After Overloading the appropriate operators, you can use objects in expression in just the
same way that you use c++ built in data types.
• Operator function defines that the operations that the overloaded operator will perform relative
to the class.
• An operator function is created using the keyword operator.
• Operator functions can be either members or nonmembers of a class.
• Nonmember operator functions are almost always friend functions of the class.
##include <iostream> int main()
using namespace std; {
demo aa,bb,cc;
class MyNumber { aa.getdata();
public: bb.getdata();
void getdata() cc=aa+bb;
{ aa.putdata();
cout<<"\nEnter a Number:"; bb.putdata();
cin>>a; cc.putdata();
} return 0;
void putdata() }
{
cout<<"\nValue of a="<<a;
}
demo operator+(demo bb)
{
demo cc;
cc.a=a+bb.a;
return cc;
}
};
Creating a member operator function
• A member operator function takes this general form:
Return-type class-name::operator#(arg-list)
{
//operations
}
When we create an operator function, substitute the operator for the #
For example, if you are overloading the / operator, use operator /.
When you are overloading a unary operator , arg-list will be empty.
When you are overloading binary operators, arg-list will contain one parameter.
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
logitude = lg;
latitude = lt;
}
loc operator+(loc op2);
};
//overload + for loc
loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.logitude+logitude;
temp.latitude = op2.latitude + latitude;
return temp;
}
int main()
{
loc ob1(10, 20), ob2(5, 30);
ob1.show(); //displays 10 20
ob2.show(); //displays 5 30
//Allocate an object.
void *operator new(size_t size)
{
/*perform allocation. Throw bad_alloc on failure.constructor called automatically.*/
return pointer_to_memory;
}
// Delete an object.
void operator delete(void *p)
{
/*free memory pointed by p.
Destructure called automatically.*/
}