Assignment Operators Overloading in C++

Posted in /  

Assignment Operators Overloading in C++
vinaykhatri

Vinay Khatri
Last updated on March 29, 2024

    The assignment operator (=) in C++ is used to assign the values to the variables and like other operators using the Operator Overloading we can overload or redefine the task of assignment operator for Class-based user-defined objects.

    Syntax to Overload Assignment Operator

    return_type operator = (Class_name object_name)
    {
    // Redefining Body:
    }

    Example

    #include <iostream>
    #include<cstring>
    using namespace std;
    class Displacement
    {
       private :
          int x;
          char n[20];
    
       public:
            Displacement(int initialize, char name[]) //counstructor
               {
                  x=initialize;
                  strcpy(n,name);
                  cout<<"you have created an object "<<n<<" which need to displace  "<< x <<" units";
                   cout<<endl;
    
              }       
    
            void operator=(Displacement obj)
    
                 {
                      x =  obj.x;
                      cout<<"Now the displacement unit of object "<<n<< " has become: "<<x;
                 }    
    
    };
    
    int main()
    {
    
       Displacement D1(200,"D1");
       Displacement D2(100,"D2");
       D1=D2;  // calling the   void operator=(Displacement obj) method for D1 object.
       return 0;
    }

    Output

    you have created an object D1 which need to displace  200 units
    you have created an object D2 which need to displace  100 units
    Now the displacement unit of object D1 has become: 100

    Behind the code In this example, we have overload or redefined the Assignment operator for Displacement class objects. D1=D2; in this statement, the D1 object call the void operator=(Displacement obj) method and here the D2 object pass as an argument to the member functions, so we can say that the obj parameter is actually the D2 object.

    Conclusion

    We hope this article has helped you gain enough clarity on assignment operators overloading in C++. Also, we have explained how to overload an assignment operator in C++ with an example and its explanation. You can implement the above code on your own to understand it better. Happy Learning!

    People are also reading:

    Leave a Comment on this Post

    0 Comments