Search code examples
c++initializationclass-members

class member needs this-pointer at instance-initialization


I was trying to create a member (prop of class A) to a class (B). This member "prop" of class A needs to gets the "this" pointer of the newly created B-instance passed in its constructor. Just as shown in the snippet (Snippet 1) below.

However, this is failing at compile time with the error message: "A typespecifier was expected" (translated from german).

I think this is about I am not able to use the this-pointer in this context, but I do not want to go the way of Snippet 2 and use a pointer. It is just not practical for me.

Is there any way to accomplish this close to the coding style of the first snippet?

Snippet 1

class B;

class A
{
public:
    A(B* b) 
    {
       // ...
    };

};

class B 
{
public:
    A prop(this);
};

Snippet 2

class B;

class A
{
public:
    A(B* b) 
    {
       // ...
    };

};

class B 
{
public:
    B()
    {
       this->prop = new A(this);
    }

    A* prop;
};

Edit: Just figured out this snippet, but when having many of them in one class makes it really unreadable.

Snippet 3

class B;

class A
{
public:
    A(B* b)
    {
       // ...
    };

};

class B 
{
public:
    B() : prop(this) {};

    A prop;
};

Many thanks!
Sebastian


Solution

  • I got the solution by myself now.

    For non-experimental; non-c++11 standard, luri Covalisin is right.

    But if we give a look at c++11, we can do as follows:

    class B;
    
    class A
    {
    public:
        A(B* b)
        {
           // ...
        };
    
    };
    
    class B 
    {
    public:
        A prop{this};
    };
    

    this looks kinda weird, but is more like what I was looking for.