Program to overload assignment operator
#include<iostrema.h>
class number
{
int x, y;
public:
number()
{
x = 0;
y = 0;
}
number(int a, int b)
{
x = a;
y = b;
}
void display()
{
cout<<"\n x: "<<x;
cout<<"\n y: "<<y<<endl;
}
void operator = (number n1)
{
x = n1.x;
y = n1.y;
}
};
int main()
{
int m, n;
cout<<"Enter two numbers: \n"; cin>>m>>n;
number n1(m,n);
number n2;
cout<<"\n Before overloading:\n";
cout<<"\n N1=";
n1.display();
cout<<"\n N2=";
n2.display();
n2=n1;
cout<<"\n After overloading:\n";
cout<<"\n N1=";
n1.display();
cout<<"\n N2=";
n2.display();
return(0);
}
OUTPUT Enter two numbers: 3 6 Before overloading: N1= x:3 y:6 N2= x:0 y:0 After overloading: N1= x:3 y:6 N2= x:3 y:6
In C++, when assigning one object to another using the = operator, the default assignment performs a shallow copy. For classes that manage dynamic memory, this can lead to issues like double deletion or memory leaks. To prevent this, you can overload the assignment operator to implement a deep copy. In this tutorial, we’ll write a C++ program to properly overload the = operator.
Why Overload the Assignment Operator?
- Prevents shallow copy issues in dynamic memory.
- Ensures each object has its own memory space.
- Avoids runtime errors like double-free and dangling pointers.
Overloading the assignment operator is essential when your class manages resources like dynamic memory. It ensures safe and predictable behavior when copying objects. Mastering this concept strengthens your understanding of C++ memory management and object-oriented design


