I am learning about explicit
keyword in C++ using the resources listed here and as this post says:
Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions.
Now I wrote the following example that uses the explicit
copy constructor B::B(const B&)
in an implicit conversion. The example is as follows: MRE with C++14 and -fno-elide-constructors flag
struct A {
A()
{
std::cout<<"A's default ctor called"<<std::endl;
}
A(const A&)
{
std::cout<<"A's copy ctor called"<<std::endl;
}
};
class B
{
public:
B()
{
std::cout<<"B default ctor called"<<std::endl;
}
B(A)
{
std::cout<<"B's parametrized ctor called"<<std::endl;
}
explicit B(const B&)
{
std::cout<<"explicit B copy ctor called"<<std::endl;
}
};
int main()
{
B x;
//B a = x; //this fails AS EXPECTED
A y;
B p = y; //Why doesn't this fail as well? This uses the copy ctor in addition to the param ctor. How the explicit copy ctor is used here in implicit conversion
}
The output of the above program is:
B default ctor called
A's default ctor called
A's copy ctor called
B's parametrized ctor called
explicit B copy ctor called <--------------HOW IS THAT EXPLICIT CTOR IS USED HERE IN IMPLICIT CONVERSION?
So my question is that how is it possible to use an explicit copy ctor in the above implicit conversion. I mean to my current understanding I expected B p = y;
to fail just like the copy initialization B a = x;
fails. I want to know is this allowed by the standard or is it a compiler bug.
Note
Note the use of -fno-elide-constructors
flag in my given demo.