C++ - Assignment Operator Overloading
Assignment operator (=) is a binary operator which means it requires two operand to produce a new value. The declaration is identical to any binary operator, with the following exception:
- It can not be declared as a non-member function. It must be a non-static member function.
- It is not inherited by derived classes.
- If operator= is not specified in a class, compiler generates a default operator= and inserts it into the code.
Example: overloading assignment operator
In the example below, assignment operator (=) is overloaded. It is used to assign value from one vector object to another vector object.
#include <iostream> using namespace std; class vector { public: float x, y; //class constructor vector(float x, float y) { this->x = x; this->y = y; } //function to display vector void displayVector() { cout<<"("<<x<<", "<<y<<")\n"; } //function for overloading = vector operator= (const vector v) { this->x = v.x; this->y = v.y; return *this; } }; int main (){ vector v1(10, 15), v2(5, 25); cout<<"Before assignment:\n"; v1.displayVector(); v2.displayVector(); //using overloaded = operator v1 = v2; cout<<"\nAfter assignment:\n"; v1.displayVector(); v2.displayVector(); return 0; }
The output of the above code will be:
Before assignment: (10, 15) (5, 25) After assignment: (5, 25) (5, 25)
❮ C++ - Operator Overloading