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.
/*
* C++ Program to Demonstrate Overloading of Assignment (=) Operator
*/
#include <iostream>
using namespace std;
class Int {
int i;
public:
Int(int ii = 0) : i(ii) { }
Int operator=(const Int& ii) { i = ii.i; }
int get() { return i; }
void set(int ii) { i = ii; }
};
int main()
{
Int a(10), b(20);
cout << "Initial values" << endl;
cout << "a::i = " << a.get() << endl;
cout << "b::i = " << b.get() << endl;
cout << "After operation a = b" << endl;
a = b;
cout << "a::i = " << a.get() << endl;
cout << "b::i = " << b.get() << endl;
}
$ 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.
Related Posts:
- Practice Programming MCQs
- Check Computer Science Books
- Apply for C++ Internship
- Practice Computer Science MCQs
- Apply for Computer Science Internship