When is the constructor called?
In which of the following is the constructor of myClass called?
1. myClass class1;
2. myClass* class1;
3. myCl开发者_如何学运维ass* class1 = new myClass;
Thanks a lot
- Yes - default constructor, instance created on stack
- No
- Yes - default constructor, instance created on heap
- The statement would instatiate an object on the stack, call c'tor.
- Defines only a pointer variable on the stack, no constructor is called.
- The new operator would create an object in free store (usually the heap) and call c'tor.
But this code will not instantiate any object, as it does not compile. ;-) Try this one:
myClass class1;
myClass* class2;
myClass* class3 = new myClass;
- class 1 is a local variable (on the stack), constructor called.
- class 2 is a pointer, no constructor called.
- class 3 is a pointer, the constructor is called, when new is executed.
In both #1 and #3 since you are actually making an instance of the object. In #2 you are merely declaring a pointer that doesn't point to an instance.
1 and 3, because in them you create a myClass object.
The constructor is called in cases 1 and 3 when a class is instantiated. The other one (2) only declares a pointer.
精彩评论