What's wrong with this struct with override?

I have this, but it's not working.
typedef struct complex {
double Re;
double Im;
complex operator=(double val){
complex retval;
retval.Re = val;
retval.Im = 0;
return retval;
}
} complex;

It's an overload of the assignment operator "=" and is supposed to make it easy to convert a real value into a complex value. The end result of the operation is intended that the complex value's real part will hold the desired number, and its imaginary part will be 0 (zero). However, I find that its real part remains 0. The assignment never gets performed. Please tell me what I'm doing wrong.
https://en.cppreference.com/w/cpp/language/copy_assignment
Based on these examples, you're returning the wrong thing.
And you're not modifying 'this->Re' or 'this->Im'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>


struct complex {
    double Re;
    double Im;
    complex& operator=(double val)
    {
        Re = val;
        Im = 0;
        return *this;
    }
};


int main()
{
    complex cx;
    cx = 2.0;
    std::cout << "cx.Re: " << cx.Re << "; cx.Im: " << cx.Im << '\n';
}


Output:
cx.Re: 2; cx.Im: 0


Registered users can post here. Sign in or register to post.