Olumide
Olumide

Reputation: 5809

Using the reference to an object in the member initialzation list of its constructor

Is it okay to pass the reference to an object (of type) Container in the member initialization list of its constructor in order to initialize a member of Container as follows: (code on ideone).

#include <cstdlib>
#include <iostream>

struct Container;

struct Member
{
    Member( Container& container ) : m_container( container )
    {
    }

    Container& m_container;
};

struct Container
{
    Container() : m_member( *this )
    {
    }

    Member m_member;
};

int main()
{
    Container c;
    return EXIT_SUCCESS;
}

The code compiles but I'm not sure if its standard.

Upvotes: 4

Views: 96

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

That's fine; the member reference is initialised to refer to the object that was passed as an argument.

However, since the Container is still under construction, you mustn't access it in that constructor; the only thing you can do with the reference is initialise another reference.

You must also make sure that you don't use that reference after the container is destroyed. In this example, it's fine - m_member, and the reference it contains, are destroyed along with the container.

Upvotes: 5

Mat
Mat

Reputation: 206689

That's ok, but do note that container in Member's constructor is not completely constructed yet, so you can't do anything with it except store that reference.

Upvotes: 4

Related Questions