I have this code:
#include <iostream>
using namespace std;
class complex
{
double re;
double im;
public:
complex(): re(0), im(0) {}
complex(double x) {re = x, im = x;}
complex(double x, double y) {re=x, im =y;}
void print() {cout << re << " " << im;}
};
int main()
{
complex c1;
double i=2;
c1 = i;
c1.print();
return 0;
}
My question is, why the code in this line compiles.
c1 = i;
The compiler gives no error(or warning), why?
Let's examine what happens in the line.
c1 = i;
What happens is that operator= is called for class complex, which, in this case, is implicitly defined.
/////////////////////////////////////
//implicit copy assignment operator//
/////////////////////////////////////
complex& operator=(const complex& cmp)
{
//the default implicit function of this operator is copying every member of cmp into this.
}
So it takes const complex& as argument, which can be bound to rvalue of type complex, then the compiler searches to see if there is a constructor accepting double parameter, so the expression is resolved into.
c1 = complex(i);
Which, obviously, can be executed.
c1 = i invokes the constructor complex(double x) {re = x, im = x;}. If you'd prefer it didn't you can specify the constructor as explicit, like so:
explicit complex(double x) {re = x, im = x;}
Then the compiler would issue an error @ c1 = i;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With