How to Create Custom Assignment Operator in C++?
Last Updated :
19 Feb, 2024
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++
#include <iostream>
using namespace std;
class Date {
public :
int day, month, year;
Date( int d, int m, int y)
: day(d)
, month(m)
, year(y)
{
}
Date& operator=( const Date& other)
{
if ( this != &other) {
day = other.day;
month = other.month;
year = other.year;
}
return * this ;
}
void print()
{
cout << day << "/" << month << "/" << year << endl;
}
};
int main()
{
Date d1(1, 1, 2000);
Date d2(2, 2, 2002);
cout << "Initial Dates: " << endl;
d1.print();
d2.print();
d1 = d2;
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
Share your thoughts in the comments
Please Login to comment...