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,653
  • 2
  • 22
  • 31

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
  • 65,167
  • 30
  • 162
  • 315
Donotalo
  • 12,378
  • 23
  • 79
  • 116
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
  • 216,767
  • 17
  • 275
  • 509
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
  • 66,530
  • 15
  • 117
  • 170