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 below example, 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); v1.displayVector(); v2.displayVector(); v1 = v2; v1.displayVector(); v2.displayVector(); return 0; }
The output of the above code will be:
(10, 15) (5, 25) (5, 25) (5, 25)
❮ C++ - Operator Overloading