A* obj = new A;
A* obj = new A() ; // why this bracket needed here
because if A is a builtin type like int, then
int * obj = new int() will zero initialise the newly created int.
So this particular method can be used to ZERO POD stuctures and arrays.
int* parr = newint[27]();//zero initialise the array on creation
If class A contains two int variables . According to you ,all the variables are initialized to zero when I use A* obj = new A() ;
lets say
class A {
public:
int age ;
int root;
};
age & root will be ZERO .. am i right ?
btw , both the methods are calling Constructor , then how it is different from each others , who is making the difference . someone needs to tell the Constructor that, for this call , init all the variable to zero , for others use garbage value .
no, initializing to 0 only applies if it is a built in type.
however when not using dynamic memory, it seems to initialize to 1, and the compiler throws an always will be true warning, yet I remember it initializing to 0 when I tested it a few months ago, so perhaps it is something new in C++11?
On a type I just made: The assembly output shows no difference.
When you don't want to call any parameters you can just go ahead and skip the parentheses.
On an integer: The assembly is different.
The difference is that without parentheses the value is not initialized, and with parentheses it is initialized.
To summarize:
You should always use parentheses, unless you have a good reason not to.
yes, I get the same, however only with dynamic memory, without it I can only compile the program without parenthesis, unless I have a user-defined constructor that accepts arguments, and even then I have to pass arguments to it.
@Zephilinox
The reason you can't use parenthesis is because A obj();
is a function declaration of a function named obj returning an A.
You can get the same problem with constructors that take arguments.
Example: If there is an constructor accepting an int and you call the constructor like this
1 2
int v = 0;
A obj(int(v));
This is also a function declaration of a function with an int parameter.
Note that A obj;
will not initialize the members age and root.
@peter87 ,
I have a class which has a param c'tor , now how can i create the obj statically .
I know there is no direct way like dynamic . Is there any work around to do the same .
Using a constructor with parameters is usually not a problem. In my example I intentionally wrote it in a way that doesn't work as intended to demonstrate that the problem also exist for constructors with parameters. You probably don't have to do anything special, just pass the arguments as usual.