1

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(); ?

Community
  • 1
  • 1
Roger
  • 2,823
  • 3
  • 25
  • 32

3 Answers3

2

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

iammilind
  • 68,093
  • 33
  • 169
  • 336
Donotalo
  • 12,748
  • 25
  • 83
  • 121
1

Ỳ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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176