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?

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is so much more accurate than mine, dammit
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... 

4 Comments

You can do int x{}; nowadays :-)
@KerrekSB: Good point ;) Doesn't really help me make a comparison with something "familiar" though!
Hehe, no. I think last time we concluded that the best you can do for automatic objects is int x((int()); or so.
@KerrekSB: Lol yes, was just playing with that and decided not to bother any further ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.