Assignment Operators Overloading in C++

In this tutorial we shall see how to overload assignment operator “=”.

#include <iostream>
// for more tutorials check www.prodevelopertutorial.com
using namespace std;

class MyClass
{
    private:
        int num_1;
        int num_2;

    public:
        MyClass(int a, int b): num_1(a), num_2(b){ }
        
      void operator = (const MyClass &obj ) 
      { 
         num_1 = obj.num_1;
         num_2 = obj.num_2;
      }
      
      void display() 
      {
         cout << "num_1 " << num_1 <<  " num_2:" <<  num_2 << endl;
      }
    
};

int main(void)
{
    MyClass obj_1(10, 20);
    obj_1.display();
    
    MyClass obj_2 =  obj_1;
    obj_2.display();
    
}

Output:

num_1 10 num_2:20
num_1 10 num_2:20
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *