Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' in constructor and objects creation

Tags:

c++

object

this

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 ?

like image 369
Pierre Fourgeaud Avatar asked Dec 27 '22 00:12

Pierre Fourgeaud


2 Answers

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.
like image 63
Sergey Kalinichenko Avatar answered Jan 09 '23 16:01

Sergey Kalinichenko


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.

like image 40
Taimour Avatar answered Jan 09 '23 15:01

Taimour