I've not been able to find a conclusive answer to this so far. When is it safe to call
this-> a = 5; //case 2
class bar: public baz
baz(this)//case 3 - assuming baz has a valid constructor
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:
ahas been initialised at that point. Initialising
awith the value of
bwould be undefined, since
bis initialised after
fooconstructor. 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.
), but dangerous if you tried to use the pointer to access the object.
thisdoes not yet point to a valid
barobject (only the
foopart has been initialised) so accessing members of
barcould give undefined behaviour. Simply checking whether the pointer is non-null is fine, and will always give
true(whether or not you apply a pointless cast).