user2256825
user2256825

Reputation: 604

Whats the difference in creating an object using the different new expression syntaxes

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

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

From cppreference on the new expression

For non-array type, the single object is constructed in the acquired memory area.

If type is an array type, an array of objects is 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

Related Questions