'this' in constructor and objects creation
c++, object, this
Solution
Since the memory for the object and its members is allocated before the call of the constructor, the value of `this` pointer itself is not the issue: it's the members that you might dereference off of it that may be an issue.
Your first code fragment is valid, because `this->m_A` is identical to `m_A`, which is a valid expression.
Your second code fragment may or may not be OK, depending on what the constructor of `SecondClass` does:
- If `SecondClass` constructor simply stores the pointer to `FirstClass` for future use, this is OK
- If `SecondClass` constructor calls methods off of the pointer to `FirstClass` passed into it, this is not OK, because the instance to which the `this` pointer is pointing has not been initialized.
Problem
I read some articles when it is said that you should not use the 'this' keyword in constructor and others saying the exact opposite.... Now my main question is : Is it safe and is it a good practice to use 'this' in a constructor ? This question lead to others : - How an object creation is proceed ? - When are the members of a class created ? Before the constructor is called ? Here is some examples working with VS2012 on windows 7 : ``` class FirstClass { int m_A; public: FirstClass( int a ) : m_A( a ) { std::cout << this->m_A << std::endl; // ^^^^ } }; ``` and : ``` class ThirdClass; // forward decl class SecondClass { public: SecondClass( ThirdClass* iTC ) { // ... } }; class ThirdClass { SecondClass* m_SC; public: ThirdClass(): m_SC( new SecondClass( this ) ) // ^^^^ { //... } }; ``` Those examples are working but is there a probability to have an undefined behavior ?