So I'm still kind of figuring out the semantics of C++ references here.
I have a class that has a reference as a member, and I initialize the reference in the constructor.
template<class T>
class AVLNode {
private:
T & data;
public:
AVLNode(T & newData) {
data = newData;
}
};
But I get this error on the constructor line:
error: uninitialized reference member ‘AVLNode<int>::data’ [-fpermissive]
I don't get this, I initialize the reference as soon as the class is constructed so there shouldn't be a problem with the reference being uninitialized right?
There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.
If an rvalue reference or a nonvolatile const lvalue reference r to type T is to be initialized by the expression e , and T is reference-compatible with U , reference r can be initialized by expression e and bound directly to e or a base class subobject of e unless T is an inaccessible or ambiguous base class of U .
Once initialized, we cannot reinitialize a reference. Pointers can be reinitialized any number of time. You can never have a NULL reference.
Since data
is a reference, you must initialize it at constructor initializer:
AVLNode(T & newData): data(newData) {
}
You may find this post useful: reference member variable must be initialized at constructor initialization list. You may also need to understand the difference between initialization
and assignment
when you write a class's constructor.
Quoting from C++ Primer pp455:
Some members must be initialized in the constructor initializer. For such members, assigning to them in the constructor body doesn't work. Members of a class type that do not have default constructor and members that are const or reference types must be initialized in the constructor initializer regardless of type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With