Update: The suggested duplicate only addresses part of this question. The key to understand what is going on (the fact that a temporary reference is first created) isn't explained there.
This is my first time with implicit conversions, so I wrote this:
class A {};
class B {
public:
B(A& other) {}
// Copy constructor
B(const B& other) {}
};
int main() {
A foo;
B bar = foo;
}
This compiles as expected, but if I remove the const
, my compiler (gcc version 4.8.4) yields at the assignment, with an error message I'm not able to make sense of:
test.cc: In function ‘int main()’:
test.cc:12:13: error: no matching function for call to ‘B::B(B)’
B bar = foo;
^
test.cc:12:13: note: candidates are:
test.cc:7:5: note: B::B(B&)
B(B& other) {}
^
test.cc:7:5: note: no known conversion for argument 1 from ‘B’ to ‘B&’
test.cc:5:5: note: B::B(A&)
B(A& other) {}
^
test.cc:5:5: note: no known conversion for argument 1 from ‘B’ to ‘A&’
Is that valid C++ code? Why does it say no matching function for call to ‘B::B(B)’
when I'm trying to assign an A
to begin with?