Operator Overloading
Operator Overloading
#include <iostream>
class Complex {
void print()
private: {
int real, imag;
cout << real << " + i" << imag << '\n';
public: }
Complex(int r = 0, int i = 0)
{ };
real = r;
imag = i;
} int main()
// This is automatically called when '+' is used with {
// between two Complex objects
Complex c1(10, 5), c2(2, 4);
Complex operator+(Complex const& obj)
{ Complex c3 = c1 + c2;
Complex res;
res.real = real + obj.real;
c3.print();
res.imag = imag + obj.imag; return 0;
return res;
} }
Overloading New and Delete operator in c+
+
The new and delete operators can also be overloaded like other
operators in C++. New and Delete operators can be overloaded
globally or they can be overloaded for specific classes.
• If these operators are overloaded using member function for
a class, it means that these operators are overloaded only for
that specific class.
• If overloading is done outside a class (i.e. it is not a
member function of a class), the overloaded ‘new’ and
‘delete’ will be called anytime you make use of these
operators (within classes or outside classes). This is global
overloading.
The syntax for overloading the new operator :
void* operator new(size_t size);
The overloaded new operator receives size of type size_t, which
specifies the number of bytes of memory to be allocated. The return
type of the overloaded new must be void*.The overloaded function
returns a pointer to the beginning of the block of memory allocated.
Syntax for overloading the delete operator :
void operator delete(void*);
Input: x = (y = 5, y + 2)
Output: x = 7, y = 5
Explanation:
In the above expression:
It would first assign the value 5 to y, and then assign y + 2 to variable x.
So, at the end ‘x’ would contain the value 7 while variable ‘y’ would
contain value 7.
C++ program to illustrate the
overloading the comma operator
#include <iostream> comma operator+(comma ob2);
comma operator, (comma ob2);
class comma {
int x, y; };
public:
// Function to overload the + operator
// Default Constructor
comma() {} comma comma::operator+(comma ob2)
{
// Parameterized Constructor comma temp;
comma(int X, int Y)
{
x = X; // Update the value temp
y = Y; temp.x = ob2.x + x;
}
temp.y = ob2.y + y;
// Function to display the value
void display() // Return the value temp
{ return temp;
cout << "x=" << x << " ";
cout << "y=" << y << " ";
}
}
// Function to overload the, operator // Driver code
comma comma::operator, (comma ob2) int main()
{
{
// Initialize objects
comma temp;
comma ob1(10, 20), ob2(5, 30), ob3(1, 1);