dyesdyes
dyesdyes

Reputation: 1217

Difference between ClassName variable(arg1); and ClassName variable = ClassName (arg1);

How do you call these 2 different ways bellow and how are they different?

ClassName variable(arg1); 

and

ClassName variable = ClassName(arg1);

Upvotes: 0

Views: 64

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254631

ClassName variable(arg1); 

This is direct-initialisation. Assuming it's a class type, the object is initialised by passing the arguments to a suitable constructor. It's an error if there is no suitable constructor.

ClassName variable = ClassName(arg1);

This is copy-initialisation. Conceptually, it creates and direct-initialises a temporary; then initialises the variable by copying or moving the temporary. It's an error if there is no suitable move or copy constructor.

In practice, the copy or move is likely to be elided, so the result will be identical to direct-initialisation - except that there must still be an accessible move or copy constructor, even if it's not actually used.

Upvotes: 5

Raxvan
Raxvan

Reputation: 6505

case 1:
ClassName variable(arg1); 
//will initialize variable directly with the type constructor

case 2:
ClassName variable = ClassName(arg1); 
//should initialize variable directly with a copy of the rvalue
//however because of RVO optimiziation this is tha same as case 1

RVO is an optimization from the compiler that removes unnecessary calls to construct/copy/destruct and in this case they are the same.

Upvotes: 2

Related Questions