vkaul11
vkaul11

Reputation: 4214

constructing a new object and assignment in the same step

const ClassA& curShot = vec_shots[curShotIndx];

In the above code the curShot object is constructed and assigned at the same step. My question is which constructor is used in the above statement. I thought it will be the default constructor followed by the assignment operator, but it seems to call the copy constructor instead. Why is that the case?

Upvotes: 1

Views: 123

Answers (4)

Luchian Grigore
Luchian Grigore

Reputation: 258618

No constructor is used, curShot is a reference, an alias to an already existing object, not a stand-alone object by itself.

Also, initialization and assignment cannot be done at the same step. For example, say you had

 ClassA original;
 ClassA copy = original;

Here, copy is not assigned original, it's initalized using original. This is called copy initialization.

If you did

 ClassA copy2(original);

this would be called direct initialization.

The copy constructor would be called in both instances. (copy elision can occur, so it might not be called, but it must be available)

Assignment is when you use operator = on an already existing object:

 ClassA x;
 ClassA y;
 x = y;     //assignment

Upvotes: 1

Barney Szabolcs
Barney Szabolcs

Reputation: 12524

Since you wrote "it seems to call copy constructor", I assume the ampersand in your question is a typo.
In that case, if you would do

const ClassA curShot = vec_shots[curShotIndx];

it is evaluated as copy construction. It is just the same as the ugly const ClassA curShot( vec_shots[curShotIndx] ).

However, if you write

ClassA curShot;  // I skipped the "const", because otherwise the example would be invalid.
curShot = vec_shots[curShotIndx]; 

then a default constructor gets called and an opearator= is called on the second line.


Moreover, "=" so much can mean calling NEITHER copy constructor NOR operator=, that you can have this:

const ClassA f(){ return ClassA(); }
//...
const ClassA curShot = f();  // we would expect here a copy constructor call

Here -- if the compiler uses return value optimization and usually it does -- only a default constructor gets called for curShot.

Upvotes: 1

Andreas Fester
Andreas Fester

Reputation: 36650

What happens is that

vec_shots[curShotIndx];

returns a reference which you assign to const ClassA& curShot. There is no object creation involved in this step. Therefore no constructor is invoked (neither default nor copy constructor).

The assignment operator is not invoked either since you are not assigning one object instance to another, but only a reference. You are not handling more than one (existing) object instance in this code. So, no construction or assignment is invoked.

Upvotes: 4

TieDad
TieDad

Reputation: 9929

This statement just define curShot as a reference, it's not a new object.

Upvotes: 0

Related Questions