0

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

Assuming Obj is not a special class

Obj* obj = new Object;

vs

Obj* obj = new Object();

Whats the difference exactly?

Community
  • 1
  • 1
zetavolt
  • 2,989
  • 1
  • 23
  • 33
  • 3
    http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new/620402 – buck Aug 16 '11 at 20:11

2 Answers2

2

For objects, there is no difference - each will call the default constructor.

For "Plain Old Data" (POD) types there's a big difference. The first form will be uninitialized data (whatever was leftover in memory), the other will give it a known default value.

int* p1 = new int;   // *p1 == ???
int* p2 = new int(); // *p2 == 0
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

For your exact example, there is no difference if the type is non-POD. There is one difference for 3 cases :

1. When it's a primitive type :

int* pi = new int();

In this case, the () means that it have to be initialized to the default value. For int-based types and floating types, it's 0. So here, *pi == 0.

2. When it's an array of primitive type:

int* ai = new int[42]();

It means the same : all the objects will be initialized to the default value, here 0. So in this example, all elements from *ai to *(ai+41) will be equal to 0.

3. If the type is a POD, then the default initialization is done on all members.

By the way, you can also initialize default values of primitive types in initializer lists :

class myType
{
public:
    myType() : m_k(), m_t(){} // m_k == 0 && m_t ==0

private:

    int m_k;
    double m_t;
}; 

In your example, the meaning of () is the same but for non-primitive types, the default constructors are called implicitely, making the () non required. For consistency it's still used because that way you use the same syntax for every object creations. (that said, the new initialization syntax in C++0x makes it even more easy to have the same syntax for any kind of initialization).

Klaim
  • 67,274
  • 36
  • 133
  • 188
  • For the exact example, it is unknown whether it makes a difference. It depends on the definition of `Object` (i.e. what *not a special class* means), if it is POD they differ, if it has a default constructor then it does not matter at all. – David Rodríguez - dribeas Aug 16 '11 at 20:17
  • Ah yes I forgot about the POD case XD – Klaim Aug 16 '11 at 20:19