An operator that can be critical to overload is the assignment operator. The compiler automatically generates an assignment operator for every new data type. That assignment operator looks something like this:
Rational& Rational::operator=(const Rational& other) {
// copy the values from other into this
m_numerator = other.m_numerator;
m_denominator = other.m_denominator;
return *this; // return a reference to the updated object
}
This is the code that gets called when we write something like r1 = r2;. The compiler translates that expression into r1.operator=(r2). In the context of the function call, r2 is other and r1 is this, the object running the code. The operator= will take the values from other and assign them to this. Then, a reference to r1 is returned, just in case the assignment is being used in an even larger expression. (r3 = r2 = r1 is legal in C++. It means copy r1 into r2 and then copy r2 into r3.)
The automatic assignment operator for Rational copies the numerator and denominator. Which is exactly what we want. But in more complex objects, we might not want to make a simple copy. Any object that manages memory or external resources will likely need more complex behavior to ensure the proper thing happens when we make a copy. For those objects, we will need to manually define a operator=. Doing that will prevent the simple default one from being used.
This codelens has a very simple version of the Rational class and a custom implementation of the assignment operator. It uses the custom operator to mark when an object is a copy of something else. The animation will start just before the assignment operator runs.
In this case, overloading the assignment operator allows us to make sure that Rational objects are not perfectly copied. We donβt use the m_isCopy variable to do anything interesting, but it is an illustration of how we can adjust what happens when = is used to copy an object.
The details are beyond the scope of this book, but it is worth being aware that when you mix inheritance and custom assignment operators, there are significant complexities to worry about. If you ever need to do so, you should research βvirtual assignment operatorsβ.