Search code examples
c++operator-overloadingassignment-operator

Assignment Operator Overload in c++


I realize that there are examples after examples of overloading the assignment operator on the web, but I have spent the last few hours trying to implement them in my program and figure out how they work and I just can't seem to do it and any help would be greatly appreciated.

I am trying to implement an overloaded assignment operator function.

I have 3 files working, the Complex.h header file, a Complex.cpp definition file, and a .cpp file I'm using as a driver to test my Complex class.

In the Complex.h header file my prototype for the assignment operator:

Complex &operator= (Complex&);

And so far what I have for the definition of the overloaded operator in my .cpp file is:

    Complex &Complex::operator=(Complex& first)
    {
         if (real == first.real && imaginary == first.imaginary)
             return Complex(real, imaginary);

         return first;
    };

And the way I'm calling my assignment operator in my functions is:

   x = y - z;

So specifically, my problem is that when I call the overloaded assignment operator with x = y -z, it doesn't assign the passed in value to x when I return the passed in value and I'm unable to figure out why from numerous examples and explanations on the web, any help would be greatly appreciated and I thank you for any help ahead of time.


Solution

  • I think you need the following operator definition

    Complex & Complex::operator =( const Complex &first )
    {
         real = first.real;
         imaginary = first.imaginary;
    
         return *this;
    };
    

    You have to return reference to the object that is assigned to. Also the parameter should be a constant reference. In this case you may bind the reference to a temporary object or you have to write also a move assignment operator.

    In your implementation of the copy assignment operator you do not change the assigned object.:) You simply create a temporary and return reference to this temporary or return reference to first.