In C++, the assignment operator (=) is used to assign a value to a variable. However, sometimes the default behavior of the assignment operator may not be suitable for certain user-defined types. To address this, C++ allows overloading of the assignment operator, enabling custom behavior when assigning values to objects of user-defined classes.
Overloading the assignment operator allows customizing the behavior of assignment for objects of a class. This is particularly useful when deep copying is required, or when additional actions need to be performed during assignment.
#include
class Point {
public:
int x, y;
// Default constructor
Point() : x(0), y(0) {}
// Overloaded assignment operator
Point& operator=(const Point& rhs) {
if (this != &rhs) { // Self-assignment check (optional)
x = rhs.x;
y = rhs.y;
}
return *this;
}
// Function to display point coordinates
void display() const {
std::cout << "(" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Point p1(3, 5);
Point p2;
p2 = p1; // Calls the overloaded assignment operator
p1.display(); // Output: (3, 5)
p2.display(); // Output: (3, 5)
}
// output //
(3, 5)
(3, 5)
Point
class has member variables x
and y
to store point coordinates.operator=
) takes a constant reference (const Point& rhs
) to the source object.if (this != &rhs)
) is optional but prevents unnecessary copying when assigning the same object to itself.*this
) are assigned the values from the source object (rhs
).*this
) to allow for chaining assignments (e.g., p1 = p2 = p3
).Overloading the assignment operator in C++ allows customization of assignment behavior for user-defined types. By providing a custom implementation, we can ensure that assignments behave as expected for objects of our classes, enabling more intuitive and efficient code.Happy coding !❤️