Reputation:
So I have this code(stolen from cplusplus.com):
class A {};
class B {
public:
explicit B (const A& x) {}
B& operator= (const A& x) {return *this;}
operator A() {return A();}
};
void fn (B x) {}
int main ()
{
A foo;
B bar (foo);
bar = foo;
foo = bar;
// fn (foo); // not allowed for explicit ctor.
fn (bar);
return 0;
}
So the conversion constructor can only be called explicitly and thereby fn(foo);
is not allowed. This made me confused, because why can you do B bar (foo);
if you cannot do fn(foo);
, I mean doesn't fn(foo) also end up in initializing an object of type B to an object of type A, like in the statement B bar (foo);
, so what are they both not generating an error? What is particularly explicit in B bar (foo);
that is not explicit in the function call?
Upvotes: 1
Views: 113
Reputation: 21510
Doing B bar(foo)
means that you are calling the constructor of B
with foo as the argument, this is an explicit
construction. Whereas when you call fn(foo)
the compiler tries to implicitly convert foo
to match the function argument type, and this is an implicit
conversion and is therefore not allowed since your convert constructor is marked explicit
.
Upvotes: 4