Initializing a reference variable in the class constructor

So, I still understand the semantics of C ++ references.

I have a class that has a link as a member, and I initialize the link in the constructor.

template<class T> class AVLNode { private: T & data; public: AVLNode(T & newData) { data = newData; } }; 

But I get this error in the constructor line:

 error: uninitialized reference member 'AVLNode<int>::data' [-fpermissive] 

I do not get this, I initialize the link as soon as the class is built, so there should be no problem with uninitializing the link correctly?

+4
source share
1 answer

Since data is a reference, you must initialize it in the constructor initializer:

 AVLNode(T & newData): data(newData) { } 

You may find this post helpful: the link element variable should be initialized in the constructor initialization list . You may also need to understand the difference between initialization and assignment when writing a class constructor.

Quote from C ++ Primer pp455:

Some elements must be initialized in the constructor initializer. For such members, assigning them to the constructor body does not work. Members of a class type that do not have a default constructor and members that are const or reference types must be initialized in the constructor initializer, regardless of type.

+13
source

Source: https://habr.com/ru/post/1484105/


All Articles