Within any non-static member function, this
points to the object that the function was called on. It’s safe to use as long as that’s a valid object.
Within the body of a constructor or destructor, there is a valid object of the class currently being constructed. However, if this is the base sub-object of some derived class, then only the base sub-object is valid at that time; so it’s generally not safe to down-cast and try to access members of the derived class. For the same reason, you need to be careful calling virtual functions here, since they are dispatched according to the class being created or destroyed, not the final overrider.
Within the initialiser list of a constructor, you’ll need to be careful only to access members that have been initialised; that is, members declared before the one currently being initialised.
Up-casting to a base class is always safe, since base sub-objects are always initialised first.
For the specific examples you just added to the question:
- case 1 is fine (if fragile), since
a
has been initialised at that point. Initialisinga
with the value ofb
would be undefined, sinceb
is initialised aftera
. - case 2 is fine: all members have been initialised at that point.
- case 3 won’t compile, since there’s no suitable
foo
constructor. If there were, then it would depend on what that constructor did with it – whether or not it tried to access members before they were initialised. - case 4 would be well-formed if you added the missing
)
, but dangerous if you tried to use the pointer to access the object.this
does not yet point to a validbar
object (only thefoo
part has been initialised) so accessing members ofbar
could give undefined behaviour. Simply checking whether the pointer is non-null is fine, and will always givetrue
(whether or not you apply a pointless cast).