I have a class which has a private attribute which is a reference to another class:
class A {
public:
A();
A(B& anotherB);
private:
B& bRef;
}
In my A(B& anotherB), I can do this:
A::A(B& anotherB)
: bRef(anotherB) {
}
But what about A()? I tried this:
A::A()
: bRef(B()) {}
But I get this error ‘error: invalid initialization of non-const reference of type ‘B&’ from a temporary of type ‘B’.
How can I call initialize B reference in A with the default constructor of B?
Thank you.
You have to have a real instance to initialize it to. Saying
: bRef(B())creates a temporary which is immediately destroyed, thus your reference would be to an object that no longer exists, thus the compiler error.You don’t need to initialize it unless you’re making some decision based on it not being initialized. In that case you can have a
bool initialized;member that you use to keep track of the state.If you want to initialize it to something like
NULL, use a pointer instead.