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 :
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 ?
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:
SecondClass
constructor simply stores the pointer to FirstClass
for future use, this is OKSecondClass
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.First, yes it is totally safe to use the 'this' keyword, In case of all those members which are on stack the 'this' keyword will work fine and those which are pointer type you must assign them memory first then use them using the 'this' keyword. if you don't assign memory and try to use them then it will create an issue. Secondly you asked that how object creation takes place and when members of class are created they are created when you make the object of the class either in main or in any function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With