7

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?

Ethan
  • 1,206
  • 3
  • 21
  • 39

1 Answers1

23

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.

Community
  • 1
  • 1
taocp
  • 23,276
  • 10
  • 49
  • 62