Technologies, computing and programming are my passions. I talk about these passions here.

Sunday, April 24, 2011

C++: Is 'this' safe in the constructor?

I've been working hard on something very interesting during the Easter holidays. Wanted to take a quick break, listen to some good music and make a blog post. Alright, my favorite Sony earbuds are on and queued the songs. Now here goes the quick post.

Very often C++ beginners get confused about when and how 'this' pointer can be used. Most common confusion is probably:

Is it safe to use 'this' in the constructor?

Having the confusion, many amateurs avoid using 'this' pointer in constructor. Well, such confusion is harmful for the programmer, project and the company funding the project.

The short answer to the question is: yes, 'this' is very safe in the constructor. All members (or objects) derived (from parent class in case of inheritance) and defined in the class 'will be' allocated and initialized before the constructor gets executed. So you can safely access the members of the class in the constructor.

Now, that was a short answer. For a comprehensive one, we need to discuss in what order objects are created and destroyed and how to use the RAII (Resource Acquisition Is Initialization) idiom. I'll try to make this the topic of my next post.

Answer to the warning question: The warning is a pretty valid one and appears when you pass 'this' pointer in the initializer list of a class. It can be both safe and unsafe depending on the use of it. 'this' pointer is not properly initialized until constructor body starts executing. So when 'this' is used to initialize a member using initializer list, the member needs to be careful as it shouldn't use the 'this' pointer to access its other members or function. However, it can safely hold the reference to 'this'.

In the above example, one might except value of b.y is 10 but the value is garbage. This is because B's constructor used A ('this') before A's member (x) was initialized. So we cannot make such use of 'this'.

Similarly, the use of 'this' can be both safe and unsafe for inheritance as well.