Kundan Kumar
Kundan Kumar

Reputation: 2002

Initialisation list with this pointer

Got confused here. Even on passing this in the initialization list, the program is being compiled and run successfully. I had the impression that on passing this here the compiler should give some error as the object had not been created here.

The output of both the couts is the same; i.e they hold the same address.

I know this is not correct programming methodology but whats exactly is happening here ?

    class foo
    {
            public:
            foo():myself( this ) {}
            foo * myself;
    };


    int main()
    {
            foo f;
            cout<<f.myself<<endl;   
            cout<<&f<<endl;
            return 0;
    }

Upvotes: 2

Views: 124

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308111

Even though the object isn't fully initialized yet, its address is known and can be assigned to a pointer.

Although this idiom isn't at all common, I could see it being used for initialization of a linked list for example.

Upvotes: 2

Related Questions