Reputation: 19
There are multiple ways of initializing an object in c++. There are two examples below, ent1 and ent2. I'm wondering what the difference is, and is one of them more 'correct' or preferred over another?
class Entity {
public:
int h;
Entity(int health) : h(health) { }
}
Entity ent1(10);
Entity ent2 = Entity(10);
Upvotes: 0
Views: 74
Reputation: 4099
In C++17, both of these are identical. Pre C++17, however, there is a subtle difference as follows:
The one below is a copy constructor. This will create an anonymous Entity and then copy over to ent2
, although the copy may be omitted subject to copy epsilon.
Entity ent2 = Entity(10);
The one below is a direct instantiation, the memory for ent1
will be allocated and value 10 will be placed in the area specified by the constructor.
Entity ent1(10);
The reason direct is preferred, in pre C++17, is because it doesn't require the extra copy step. This advantage is non-existent in C++17.
Upvotes: 2