Why the B(B&)
ctor is called, instead of B(const B&)
, in the construction of object b1
?
#include <iostream>
using namespace std;
struct B
{
int i;
B() : i(2) { }
B(B& x) : i(x.i) { cout << "Copy constructor B(B&), i = " << i << endl; }
B(const B& x) : i(x.i) { cout << "Copy constructor B(const B&), i = " << i << endl; }
};
int main()
{
B b;
B b1(b);
}
This is because overload resolution applies, and since the argument to the constructor of b1
is b
, and b
happens to be non-const lvalue, then the constructor taking non-const lvlalue is selected. And that's the first one. Interestingly, both are copy constructors, but your code would be equaly valid with just the latter one.
Because b is not const. Therefore, it matches the first copy ctor perfectly, so that's what the compiler uses.
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