Friday 24 February 2012

Should the this pointer can be used in the constructor? C++

 We can use the this pointer in the constructor in the initialization list and also in the body. However, there is a feeling that the object is not fully formed so we should not use this pointer. Let's understand the use of the this pointer with the help of the following example. The declared data members of a base class and/or the declared data members of the constructor's own class can be accessed by the constructor {body} and/or a function called from the constructor. This is possible because of the full construction of constructor's body at the time of execution. The preceding example always works.

The override in the derived class is not possible for a function called from the constructor and the {body} of a constructor which is independent of calling the virtual member function by the explicit use of the this pointer.

Please make sure that the initialization of other data member has already been done before passing the data member to another data member's initializer in this object. With the help of some straightforward language rules (independent of the specific compiler that you are using), you can confirm about the determination of initialization of data members.

Without the prior knowledge of these rules, there is no use of passing any data member from the this object.