[ACCEPTED]-Passing "this" to a function from within a constructor?-this

Accepted answer
Score: 34

When you instantiate an object in C++, the 13 code in the constructor is the last thing 12 executed. All other initialization, including 11 superclass initialization, superclass constructor 10 execution, and memory allocation happens 9 beforehand. The code in the constructor 8 is really just to perform additional initialization 7 once the object is constructed. So it is 6 perfectly valid to use a "this" pointer 5 in a class' constructor and assume that 4 it points to a completely constructed object.

Of 3 course, you still need to beware of uninitialized 2 member variables, if you haven't already 1 initialized them in your constructor code.

Score: 4

You can find a good answer to this here (C++ FAQ).

All 9 inherited members and members of the calling 8 class are guaranteed to have been constructed 7 at the start of the constructor's code execution 6 and so can be referenced safely within it.

The 5 main gotcha is that you should not call 4 virtual functions on this. Most times I've 3 tried this it just ends up calling the base 2 class's function, but I believe the standard 1 says the result is undefined.

Score: 0

As a side-note on the presented code, I 3 would instead templatize the void*:

class Stuff
    template <typename T>
    static void print_number(const T& t)
        std::cout << t.number;

    int number;

    Stuff(int number_)
    : number(number_)

Then you'd 2 get a compile error if the type of t doesn't 1 have a number member.

More Related questions