Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing "this" to a function from within a constructor?

People also ask

Can I pass this in constructor?

Passing this to another method/object from inside the constructor can be rather dangerous. Many guarantees that objects usually fulfill are not necessarily true, when they are looked at from inside the constructor.

Can I pass this in constructor C++?

The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.

Can we pass this in constructor in Java?

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

Can we call a function inside a constructor?

You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.


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

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


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

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

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