0

Is there a way to use a reference as a member variable without initialising it in the constructor? My problem is that I don't have the reference at hand when constructing the object.

2
  • 1
    Show what you would like to do. You may not need to perform all initialization inside the constructor, something can be done lazy when you'll need it. Commented Mar 22, 2012 at 12:14
  • Can you construct the object after you have the reference to hand? Commented Mar 22, 2012 at 12:40

3 Answers 3

4

No. References must be initialized on creation and cannot be modified thereafter. The standard states that

A reference shall be initialized to refer to a valid object or function.

If you don't have the target object at hand on construction, switch to using a pointer instead of a reference.

Sign up to request clarification or add additional context in comments.

Comments

2

> Is there a way to use a reference as a member variable without initialising it in the constructor?

No, references must be initialized in constructor initializer list

> My problem is that I don't have the reference at hand when constructing the object.

I guess what you meant is you don't have an object to refer to. In that case you have to go for a pointer and initialize it to NULL. Then later when you have the object make the pointer point to that. A reference cannot be used in this case as you cannot initialize reference to NULL

Comments

0

Once a reference is initialized, it will, for the time of his life, point to the same entity. Any attempt to "reseat" it results in undefined behaviour.

So short answer: If you can't initialize, you can't use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.