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,799
  • 3
  • 19
  • 37

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
  • 447,451
  • 88
  • 851
  • 1,056
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
  • 369,052
  • 73
  • 620
  • 1,021