I have the following code:
class SomeClass {};
class SomeOtherClass {
SomeClass& someObj;
public:
SomeOtherClass() {someObj = SomeClass();}
};
And I get an error on the constructor for SomeOtherClass saying Constructor for 'SomeOtherClass' must explicitly initialize the reference member 'someObj'.
So I guess my question is pretty strait forward. How do you initialize a reference?
You’re trying to store a reference to a temporary object that is being destructed immediately, so that will definately go wrong; even when using the constructor initialization lists described in the other answers.
A reference should point to an object that is being stored elsewhere, just like a pointer. Are you sure you even need to use a reference in this case?