Assignment Operator Overloading in C++
Posted by Superadmin on August 08 2022 09:40:40

Assignment Operator Overloading in C++

 

 

This C++ program demonstrates overloading of assignment (=) operator. The program defines a class, defines the assignment operator for the class, creates an instance of the class and demonstrates its use.

 

Here is the source code of the C++ program which demonstrates overloading of assignment (=) operator. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate Overloading of Assignment (=) Operator
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Int {
  8.         int i;
  9.     public:
  10.         Int(int ii = 0) : i(ii) { }
  11.         Int operator=(const Int& ii) { i = ii.i; }
  12.         int get() { return i; }
  13.         void set(int ii) { i = ii; }
  14. };
  15.  
  16. int main()
  17. {
  18.     Int a(10), b(20);
  19.  
  20.     cout << "Initial values" << endl;
  21.     cout << "a::i = " << a.get() << endl;
  22.     cout << "b::i = " << b.get() << endl;
  23.     cout << "After operation a = b" << endl;
  24.     a = b;
  25.     cout << "a::i = " << a.get() << endl;
  26.     cout << "b::i = " << b.get() << endl;
  27. }

 

$ a.out
Initial values
a::i = 10
b::i = 20
After operation a = b
a::i = 20
b::i = 20