I'm pretty sure this is a duplicate question, but I've been searching for a while and I didn't get any smarter.
Imagine this class:
class Entity {
public:
int x, y;
Entity() : x(0), y(0) { }
Entity(int x, int y) : x(x), y(y) { }
}
And here are multiple ways of initializing the class:
Entity ent1;
Entity ent2();
Entity ent3(1, 2);
Entity ent4 = Entity();
Entity ent5 = Entity(2, 3);
I also know that's it's possible make an object on the heap memory, but that's not a great mystery to me at this moment.
Here's what I think I know
ent1 - Uses the default constructor, so x=0 and y=0
ent2 - Uses the default constructor, so x=0 and y=0 (Not sure)
ent3 - Made constructor, so x=1 and y=2
ent4 - Default constructor, so x=0 and y=0
ent5 - Made constructor, so x=2 and y=3
Correct me if I'm wrong.
But my question is, what's the difference between these ways of initializing an object?
I'm not sure which one I should use when.
Entity ent1;
This statement uses default constructor of class Entity
.
Entity ent2();
This definition will be treated by compiler as a function prototype if that's possible.
Entity ent3(1, 2);
User-defined constructor is invoked for ent3
.
Entity ent4 = Entity();
This is a proper version of ent2
case. Default constructor is invoked as part of value initialization. Its form allows to avoid Most Vexing Parse - ambiguity solving principle which makes ent2
incorrect.
Entity ent5 = Entity(2, 3);
A version of ent3 case. User-defined constructor invoked as part of value initialization.
Your question is tagged as C++11, and C++11 allows uniform initialization syntax:
Entity ent12{}; // This is a legal alternative of ent2 case
Entity ent13{1, 2};
Entity ent14 = {};
Entity ent15 = Entity{2, 3};
Note that uniform initialization syntax has a caveat. E.g. this line
std::vector<int> v(10);
declares a vector of 10 elements. But this one
std::vector<int> v{10};
declares a vector initialized with single element of type int with value 10. This happens because std::vector
has a constructor with following signature defined:
vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
In case that you can't use neither () without triggering MVP nor {} without invoking undesired constructor, the value initialization assignment syntax allows to resolve the issue.