Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

You cannot initialize class member in class declaration. As you correctly noted in snippet #3 - constructor initialization list exists for the members, that require parameters to be passed to constructor.

Using an initializtion list is the best way IMHO of doing this, note, members are initialized in the order you declare them, but not the order at initializer list:

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

  A prop;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top