Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, initialize a class member with 'this' pointer during construction

I'd like to create a class that is associated to another class in some sort of parent-child relationship. For this the "child" class needs a reference to it's parent.

For example:

template <typename T>
class TEvent {
    private: T* Owner;
    public: TEvent(T* parent) : Owner(parent) {}
};

class Foo {
    private: TEvent<Foo> Froozle; // see below
};

Now the problem is that I can't initialize the Froozle instance directly, nor using the instanciation list of Foo's constructor, because this references are not allowed there. Apart from adding another method setParent(T*) (which I don't like too much because it means that I have to leave the TEvent<> instance in an invalid state), is there a way to achieve this?

like image 474
sunside Avatar asked Oct 23 '10 21:10

sunside


Video Answer


1 Answers

It is OK to use this in the initialization list, as long as it is not used to access any members that may not have been initialized yet.

like image 95
Björn Pollex Avatar answered Oct 21 '22 12:10

Björn Pollex