1

Possible Duplicate:
Do the parentheses after the type name make a difference with new?

I believe this question was already asked, but I cannot find it with a quick search.

Foo ob* = new Foo; 

Foo ob* = new Foo();

Is there a difference between these two ways of creating an object in C++? If not then is one of these considered a bad practice? Does every compiler treats it the same?

Community
  • 1
  • 1
bvk256
  • 1,837
  • 3
  • 20
  • 38
  • 3
    There is a subtle difference between using parentheses and not using parentheses, and a really detailed explanation is offered in this question: http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new – wkl Nov 14 '11 at 14:25
  • @birryree: Ah, there it is :) – Lightness Races in Orbit Nov 14 '11 at 14:26
  • http://stackoverflow.com/questions/2417065/c-does-the-default-constructor-initialize-built-in-types – Ken Brittain Nov 14 '11 at 14:27

2 Answers2

7

The first is default initialization, the second is value initialization. If Foo is of class type, they both invoke the default constructor. If Foo is fundamental (e.g. typedef int Foo;), default initialization performs no initialization, while value-initialization performs zero-initialization.

For class types and arrays, the initialization proceeds recursively to the members/elements in the expected way.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

There is no difference, other than the fact that if Foo is a built-in type then the former does not value-initialise it.

So:

new int;   // unspecified value
new int(); // 0

This matches up nicely with "normal" allocation for built-ins, too:

int x;     // unspecified value
int x = 0; // well, you can't do `int x()`, but, if you could... 
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055