How to Create Custom Assignment Operator in C++?
In C++, operator overloading allows us to redefine the behavior of an operator for a class. In this article, we will learn how to create a custom assignment operator for a class in C++.
Creating Custom Assignment (=) Operator in C++
To create a custom assignment operator, we need to define an overloaded assignment operator function in our class. The overloaded assignment operator function should have the following signature:
ClassName& operator= (const ClassName& other);
Here, ClassName is the name of the class for which we are defining the custom assignment operator and other represents the object being assigned from.
C++ Program to Write Custom Assignment Operator for a Class
The below example demonstrates how we can write our own assignment operator for our class in C++.
// C++ program to create custom assignment operator
#include <iostream>
using namespace std;
// Class to represent a Date
class Date {
public:
// Member variables for day, month, and year
int day, month, year;
// Constructor to initialize the Date object
Date(int d, int m, int y)
: day(d)
, month(m)
, year(y)
{
}
// Custom assignment operator
Date& operator=(const Date& other)
{
// Check for self-assignment
if (this != &other) {
// Copy data from other to this object
day = other.day;
month = other.month;
year = other.year;
}
return *this; // Return a reference to this object
}
// Method to print the date
void print()
{
cout << day << "/" << month << "/" << year << endl;
}
};
int main()
{
// Create two Date objects
Date d1(1, 1, 2000);
Date d2(2, 2, 2002);
// Print the initial dates
cout << "Initial Dates: " << endl;
d1.print();
d2.print();
// Assign the values of d2 to d1 using the custom
// assignment operator
d1 = d2;
// Print the dates after assignment
cout << "Dates after assignment of Date2 to Date1: "
<< endl;
d1.print();
d2.print();
return 0;
}
Output
Initial Dates: 1/1/2000 2/2/2002 Dates after assignment of Date2 to Date1: 2/2/2002 2/2/2002
The above assignment operator syntax is for copy assignment operator. It is generally recommended to also define the move assignment operator along with it. To know more, refer to this article - C++ Assignment Operator Overloading