Reputation: 604
Below are the three different ways of initialization in c++ , would you please explain whether there is any difference in these three ways if we do not have any arguments
These 3 ways work while creating an object, while returning to a function too (ex: return new myClass)
How and where exactly do each of them fit in individually when other ways fail ?
myClass *p = new myClass;
myClass *p = new myClass();
myClass *p = new myClass{}
Upvotes: 0
Views: 83
Reputation: 117856
From cppreference on the new expression
For non-array type, the single object is constructed in the acquired memory area.
- If initializer is absent, the object is default-initialized.
- If initializer is a parenthesized list of arguments, the object is direct-initialized.
- If initializer is a brace-enclosed list of arguments, the object is list-initialized.
If type is an array type, an array of objects is initialized.
- If initializer is absent, each element is default-initialized.
- If initializer is an empty pair of parentheses, each element is value-initialized.
- If initializer is a brace-enclosed list of arguments, the array is aggregate-initialized.
However in your examples since there are no arguments, they are value-initialized
Value initialization is performed when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses or braces
So for your three examples
myClass *p = new myClass; // default-initialized
myClass *p = new myClass(); // value-initialized
myClass *p = new myClass{}; // value-initialized
Upvotes: 3