Part of the answer is given in here
class foo1
{
private:
int i;
public:
foo1()
{
i=2;
}
int geti(){
return i;
}
};
class foo2
{
private:
int j;
public:
explicit foo2(foo1& obj1) //This ctor doesn't have `const` intentionally as i wanted to understand the behavior.
{
cout<<"\nctor of foo2 invoked";
j=obj1.geti();
}
};
foo1 obj1;
foo2 obj2(obj1); //THIS WORKS
foo2 obj22=obj1; //THIS DOESN'T WORK
Both of them work when the keywork explicit
is removed.
Is the following explanation correct for copy initialization( foo2 obj22=obj1
) :
At first the compiler creates a temporary object using constructor:
foo2(foo1& other) {}
then it tries to use this temporary object in the copy constructor:
foo2(foo2& other) {}
But it may not bind a temporary object with non-constant reference and it issues an error.
When you are using the equal sign then there is used so-called copy-initialization.
If yes, then shouldn't foo2(foo1& other) {}
itself be disallowed before even going further because temporary cannot be bound to non const reference?
Sorry for the long question, my confusion is basically around difference behavior for direct and copy initialization in presence/absence of explicit keyword(with/without const)