Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the { body } and even in the initialization list) if you are careful.
You must use the this pointer when: Returning the current object. Setting up relations between objects (passing this into a constructor or setter) Checking for self reference: this !=
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
The most common benefit of doing this is improved performance. If the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ — the compiler does not make a separate copy of the object.
Yes. It's safe to use this
pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions, directly or indirectly, as the object is not yet fully constructed. The object child
can store the this
pointer of Parent
for later use!
The parent this
pointer, in "pointer terms", is well-defined (otherwise how would the parent constructor know on which instance is it operating?), but:
Child
object aren't initialized yet;So, the parent object in general is still in an inconsistent state; everything the child object will do on construction on the parent object, will be done on a half-constructed object, and this in general isn't a good thing (e.g. if it calls "normal" methods - that rely on the fact that the object is fully constructed - you may get in "impossible" code paths).
Still, if all the child object do with the parent pointer in its constructor is to store it to be use it later (=> when it will be actually constructed), there's nothing wrong with it.
The behaviour is well-defined so long as you don't attempt to dereference the pointer until after the Parent
object has been completely constructed (as @Sergey says in a comment below, if the object being constructed is actually derived from Parent
, then all of its constructors must have completed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With