Users Online

· Guests Online: 17

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Assignment Operator Overloading in C++

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.79 seconds
10,801,411 unique visits