Reputation: 1
whats is the difference between these three statements in c++ ??
aa *obj;
aa *obj1 = new aa;
aa *obj2 = new aa();
where aa is a class I am confucion in last two statement .
Upvotes: 0
Views: 42
Reputation: 5642
The first does not initialize the pointer.
In the latest specification,
- If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.
- Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct initialization.
That is, if the class (you said it was a class) doesn't have a constructor, then the first form will act the same as a local scope definition and leave the memory un-initialized.
The empty initializer will force it to be initialized anyway, which gives the same results as a global variable of that type.
A class might not have a constructor, even a hidden constructor, if it contains nothing but data members of primitive types. You'll see that discussed as a "POD", or plain'ol data. For templates, the difference was found to be annoying, so the rules were refined to work, with (), uniformly for any type, even built-in types. new int()
will give a pointer to a value holding 0. new int
will give a pointer to a value holding whatever garbage happened to be at that address before.
Upvotes: 1