I'm learning about the copy constructor which has left me somewhat confused.
My text book is stating that if I want to initialize an object with an already existing object as so:
1 2
item y;
item b = y;
the last statement would actually be
item b = item(y)
and the copy constructor would be called using "y" as an argument. How would this statement work? Does the compiler create a temporary object using y as an argument and then assign this temp object to item b?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Class item {
int a;
public:
item(){ a = 0; }
item(const item& cp)
{
a = cp.getVal();
}
int getVal() {return a;}
};
Equivalent, only if the cv-unqualified types of b and y are the same.
1 2 3 4 5 6 7 8 9 10 11 12
struct A {};
struct B { explicit B(A) {} };
int main()
{
A a ;
B b1(a) ; // fine: direct initialisation
B b2 = a ; // error: copy initialisation, no implicit conversion from A to B
}
I forgot about explicit. But if item b = y; is not an error then it is equivalent to item b(y);, right? Or is there something more that I'm not thinking about?