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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.