this snippet of code is given me headache. Personally, I would like to use reference as they are neater compared to pointer, so I tried this:
include "SomeClass.h"
class FooBar
{
private:
SomeClass& member_;
public:
FooBar() : member_(SomeClass()) { };
}
I have read that you need to assign a temp variable to a class member reference, so in this case I create a dummy SomeClass() (I’m not sure if I am doing it right here. I tried it with and without specifying a default constructor). However, it does not compile in VS 2005, saying that member_ cannot be initialised.
How should I be doing this?
Thanks in advance!
1) References can not be changed to point to another object after it is initialized.
Do you really need this behavior?
2) When you initialize reference with temporary object, after this temp. object is out of scope your reference is invalid.
That’s why your code is incorrect. And you have useless member now. I’d recommend to think about two alternatives
a) Consider using pointer instead of reference.
b) Change you constructor to something like this: