C++

Assignment Operator Overloading in C++

In the article, we will discuss about the assignment operator which is represented with the equality (=) symbol in C++. Here, we use the assignment operator to overload the values of one instance to another. The right operand value is always assigned to the left operand. The assignment operator in C++ is a predefined operator that can only operate on data types that are built in. Assignment operators are set up to function only with included data types.

Example 1: Program to Overload the Assignment Operator in C++

The overloading of assignments using the assignment operator (=) is demonstrated in the following program:

#include <iostream>
using namespace std;
class PinCode
{
    private:
        int y;
    public:
        PinCode(int i)
        {
            y = i;
        }
        PinCode operator =(PinCode &num)
        {
            return PinCode(num.y);
        }
        void show()
        {
            cout<<"y = "<<y;
        }
    };
int main()
{
    PinCode num1(220);
    PinCode num2 = num1;
    num2.show();
    return 0;
}

In the given script, we create a “PinCode()”class after defining the header files. Then, we declare a private variable “y” in that class. Then, we define the public member function of the “PinCode()” class which includes a “PinCode()” constructor, the overloaded assignment operator, and the show() function.

Within the “PinCode” constructor, we pass the “i” parameter of type integer which is assigned to the “y” variable of the specified class. After this, we use the overload assignment operator and pass the “&num” object reference which returns an object of “PinCode”. Within the overload assignment operator definition, it takes the value of “y” from the parameter object and creates a new “PinCode” object.

Then, we have a definition of the show() function to display the variable “y” value in the output. Finally, we have the main() function definition where we declare two objects, “num1” and “num2,” of the “PinCode” class. The “num1” object is assigned with the value of “220” by calling a constructor, whereas the “num2” object is kept equal to the “num1” object using the assignment operator. In the end, the show() function is where we call the “num2” object to display the value of “y”.

The output displays the value of “y” which is retrieved using the assignment operator overloading:

Example 2: Program to Overload the Assignment Operator to Copy the Points from One Variable to Another in C++

Here’s another example of assignment operator overloading where we copy one team’s points to another:

#include <iostream>
using namespace std;

class TennisTeam {
    private:
        int round1;
        int round2;

    public:
        TennisTeam(int r1, int r2)
        {
            round1 = r1;
            round2 = r2;
        }
            void operator=(const TennisTeam& t)
        {
            round1 = t.round1;
            round2 = t.round2;
        }

    void points()
    {
        cout << "Round 1: " << round1 << ", Round 2: " << round2
        << endl;
    }
};

int main()
{
    TennisTeam t1(8, 4), t2(3, 9);

    cout << "TennisTeam A Points : ";
    t1.points();

    cout << "TennisTeam B points : ";
    t2.points();

    t1 = t2;

    cout << endl;

    cout << "TennisTeam A points : ";
    t1.points();

    cout << "TennisTeam B points : ";
    t2.points();

    return 0;

}

In the given script, we have the “TennisTeam” class definition where we declare two private variables, “round1” and “round2”. After this, we have a “TennisTeam” class member function which is kept public. The member functions include TennisTeam() which is a parameterized constructor as we pass “r1” and “r2” there. Inside it, we initialize the private variables “round1” and “round2” with the parameter variables.

Then, we call the overload assignment operator which refers to a TennisTeam object “t” as a parameter and returns a TennisTeam object. It creates new TennisTeam objects with the same values of round1 and round2 as the parameter objects. Next, we have a member function, “points()”, to print the points that are gained in rounds 1 and 2. The main() function is then invoked, creating and assigning the points to the “t1” and “t2” objects of the “TennisTeam” class.

Then, we use the “cout” command to print the points of “t1” and “t2” by calling them with the points() function. After that, the assignment operator moves the points from the “t1” object to the “t2” object. The copy-over points are shown to the console by calling the “t1” and “t2” objects with the points() function.

Hence, the points of the “t1” object that are assigned to “t2” using the overloading assignment operator are now shown on the console:

Example 3: Program to Overload the Assignment Operator in C++ as Virtual

In addition, we have a program where the assignment operator is defined as virtual in a particular class.

#include <iostream>
using namespace std;

struct X {
    X& operator=(char) {
        cout << "X& X::operator=(char)" << endl;
        return *this;
    }
    virtual X& operator=(const X&) {
        cout << "X& X::operator=(const X&)" << endl;
        return *this;
    }
};

struct Y : X {
    Y& operator=(char) {
        cout << "Y& Y::operator=(char)" << endl;
        return *this;
    }
    virtual Y& operator=(const X&) {
        cout << "Y& Y::operator=(const X&)" << endl;
        return *this;
    }
};

struct Z : Y { };

int main() {
    Y y1;
    Y y2;
    X* xp1 = &y1;
    X* xp2 = &y1;
    *xp1 = 'a';
    *xp2 = y2;
}

In the given script, we create the “struct X” base class. Inside the “X” class, we utilize the assignment operator function which is passed with the “char” type and then display it to the prompt. Then, we invoke the assignment operator function again and pass the “&X” reference. Note that this operator function is a virtual function that the “child” class can override.

After this, we create another class, “struct Y”, that is inherited from the “struct X” base class. Here, we call the override assignment operator functions that are inherited from the “X” base class twice. We assign the “char” type for the first assignment operator function, and the second overridden assignment operator function takes the “X&” reference. Both the overridden assignment operator functions print a different message on the console.

Next, we define another class, “Z”, which is inherited from the “Y” class. Within this class, we don’t invoke any assignment operator function because we pass the functions of the “Y” class to it. Finally, we have the main() function definition where we set the “y1” and “y2” objects of the “Y” class.

After that, we define the “xp1” and “xp2” pointers of type “*X” and assign them the “y1” object addresses using the reference(&) operator. Then, we set the assignment operator on the “xp1” and “xp2” pointers. The “xp1” pointer is assigned with the “a” character and the “xp2” pointer is assigned with the “y2” instance. Lastly, we call the “z1” instance of the “Z” class which is also set with the “a” character using the assignment operator. This generates an error during compilation because we implicitly define the “clone” assignment operator that is specified in “Z hides Y& Y::operator=(char)” class.

The output is shown on the following console where it prints the “X& X::operator=(char)” by the “xp1= ‘a’” assignment because the declaration of this function is not virtual. Then, the “print Y& Y::operator=(const &Y)” output is called by the “xp2 = y2” assignment as it was declared virtual. The compiler’s function depends on the type of object that the “xp1” pointer points to.

Conclusion

In conclusion, we are now familiar with the assignment operator overloading in C++. Thus, the assignment operator overloading causes all the object’s values to be copied to another object in C++. We have an explanation and implementation of overloading an assignment operator in the given examples.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content