I do not understand how this code is compiling. Can somebody please explain what is going on in there.
#include <iostream>
using namespace std;
class B
{
public:
B(const char* str = "\0") //default constructor
{
cout << "Constructor called" << endl;
}
B(const B &b) //copy constructor
{
cout << "Copy constructor called" << endl;
}
};
int main()
{
B ob = "copy me"; //why no compilation error.
return 0;
}
The optput is:
Constructor called
P.S.: I could not think of a more apt title than this, Anyone who can think of a better title, please modify it.
The type of
"copy me"ischar const[8], which decays tochar const *. Since the default constructor is notexplicit,"copy me"can be implicitly converted toB, and thusobcan be copy-constructed from that implicitly converted, temporaryB-object.Had the default constructor been declared
explicit, you would have had to write one of the following:Had the copy constructor also been declared
explicit, you would have had to say one of these:In practice, all copies will be elided by any half-decent compiler, and you always end up with a single default constructor invocation.