Initialization syntax for objects

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;}

};
My understanding is that since C++17 item b = y; is always equivalent to item b(y); even if b and y have different types.
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
}

http://coliru.stacked-crooked.com/a/823cf9f05808af24
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?
> But if item b = y; is not an error then it is equivalent to item b(y);, right?

Yes.

Then, item b = y; would be equivalent to item b = item(y);
with mandatory copy elision in C++17, permitted copy elision in C++14
Sorry, I don't get it, is it equivalent to item b(y) or to item b = item(y)?

item b(y) makes me think that the copy constructor is called and that is it.

item b = item(y) makes me think that first the copy constructor is called to make a temp object, and this object is then assigned to object b.
Last edited on
The b being copy constructed from the temporary item.

The "copy elision" says: "Oh no, we won't copy construct twice in a row; the value is identical so lets keep this simple."
> item b = item(y) makes me think that first the copy constructor is called to make a temp object,
> and this object is then assigned to object b.

The object b is initalised; the = here does not mean assignment.

For instance, consider: const int c = 23 ;
Here, the object of type const int is initialised. Note that one can't assign to a const object.
Topic archived. No new replies allowed.