Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a constructor ever be called on assignment?

Tags:

The output of the code below in VS2015 is "constructor".

Shouldn't it fail to compile due to the missing assignment operator?

struct A { };  struct B {     B(){}     B(const A& a) {         cout << "constructor" << endl;     }      //B& operator=(const A& a) {     //  cout << "assignment operator" << endl;     //  return *this;     //} };  int main() {     A a;     B b;     b = a;      return 0; } 
like image 437
CuriousGeorge Avatar asked Nov 07 '16 01:11

CuriousGeorge


2 Answers

Yes, when there is a conversion going on, like in your testcase.

You're effectively calling

b = B(a); 

Because B's assignment operator B& operator=(B const&) is implicitly declared, it is found during overload resolution. Because your assignment is only one conversion away from being a match (and that's exactly the number of conversions that are allowed to happen), it converts a to B and then assigns the new temporary B to b.

like image 58
krzaq Avatar answered Oct 02 '22 09:10

krzaq


Let's consider an analogous example.

double a; int b=5;  a=b; 

The only thing you can assign to a double is another double. However, an int can be converted to a double.

Similarly here, A can be converted to B, because the constructor to do so exists. And that's what happens.

like image 24
Sam Varshavchik Avatar answered Oct 02 '22 11:10

Sam Varshavchik