Question

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

I saw someone uses the constructor like this:

class Foo
{
  public: Foo();
};

int main(){
  Foo *f= new Foo;
}

what is the difference between Foo *f= new Foo; and Foo *f= new Foo(); ?

Was it helpful?

Solution

First of all the code you give will not compile. You need to have

Foo* f = new Foo()

Notice the asterisk.

Otherwise the two calls have the same result for non-primitive types. I have worked in companies where the () syntax is enforced by the styleguide and for a good reason: for primitive types there can be a difference:

int* p = new p;
cout << *p << endl; // the value is arbitrary i.e. behavior is undefined.
int* q = new int();
cout << *q << endl; // outputs 0.

It may be obvious here but imagine that Foo is a typedef for instance. So my advice is: always use the Foo() syntax.

OTHER TIPS

There is no difference between those two forms of initializations. Both will call the default constructor, given that the constructor is public.

Ỳour example probably even won't compile, you need to declare a pointer

 Foo *f = new Foo;

and there is no difference in typing new Foo or new Foo() since both run the constructor with no arguments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top