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.
-
1Show 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.Adriano Repetti– Adriano Repetti2012-03-22 12:14:11 +00:00Commented Mar 22, 2012 at 12:14
-
Can you construct the object after you have the reference to hand?Open AI - Opting Out– Open AI - Opting Out2012-03-22 12:40:11 +00:00Commented Mar 22, 2012 at 12:40
3 Answers
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.
Comments
> 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