Armada
Armada

Reputation: 728

How can I initialise a reference member in the default constructor?

Question says it all really.

Would it be better to use const pointer members instead if I were to implement the default constructor?

Upvotes: 3

Views: 6409

Answers (2)

Luc Touraille
Luc Touraille

Reputation: 82161

Well, it depends what you want your member to refer to in the default case. A possible solution is to have a default object (possibly some sort of Null object):

struct Foo
{
    Foo() : bar_(defaultBar) {}
    Foo(Bar &bar) : bar_(bar) {}

  private:
    Bar &bar_;
    static Bar defaultBar;
};

Or, as @sftrabbit shows, you can get a reference to some object from some function.

Upvotes: 3

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

You need to use the member initialization list:

struct foo
{
  const int& ref;
  foo() : ref(some_value()) { }
}

Make sure some_value() doesn't give you a temporary. It will only have its life extended until the end of the constructor:

A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

Upvotes: 5

Related Questions