Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a reference variable in a class constructor [duplicate]

Tags:

c++

reference

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?

like image 371
Ethan Avatar asked Jun 03 '13 00:06

Ethan


People also ask

How do you initialize a reference in a constructor?

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.

How do you initialize a reference 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 .

Can we reinitialize reference variable?

Once initialized, we cannot reinitialize a reference. Pointers can be reinitialized any number of time. You can never have a NULL reference.


1 Answers

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.

like image 195
taocp Avatar answered Nov 27 '22 19:11

taocp