Create a reference in a class but initialize it later?

Hello!

I believe one cannot do that because of compiler reasons... but anyway, can anyone help me solve the idea?

I would like to create a node and, when passing the element for it as a reference, avoid copying it. I just want to copy the reference to that element to save time. It'd be something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <class A>
class Node{
    public:
        Node(const A& element);
        ~Node();
    private:
        Node<A>* prev;
        Node<A>* next;
        A elem; // I would like this to be "A& elem", but I cannot initialize it yet.
};

template <class A>
Node<A>::Node(const A& element){
    this->prev = NULL;
    this->next = NULL;
    this->elem = element; // This is what I want to avoid, how could I do "&(this->elem) = element" ?
}


Thanks in advance!
Last edited on
1
2
template <class A>
Node<A>::Node(const A& element) : prev(nullptr), next(nullptr), elem(element) {}


Of course, if the reference in the class is not to a const object and the one passed in is, this wouldn't work either way.
The problem of the reference is that you need to guarantee that the lifetime of the passed object is at least as long as the Node exists.

As cire already stated: You cannot pass a reference to a const object and use it as reference to a non const object.

And a pointer is basically the same in this situation.
Thanks cire and coder for the quick replies! Now I get it :)

What is the name of that way of defining the constructor with the ":"?
Last edited on
What is the name of that way of defining the constructor with the ":"?
initializer list.

See:
http://en.cppreference.com/w/cpp/language/initializer_list
Thanks!!
Topic archived. No new replies allowed.