开发者

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


  1. Yes - default constructor, instance created on stack
  2. No
  3. Yes - default constructor, instance created on heap


  1. The statement would instatiate an object on the stack, call c'tor.
  2. Defines only a pointer variable on the stack, no constructor is called.
  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜