-2

I have a constructor for a linked list as such:

    node_t(double value, node_t * next = nullptr, node_t * prev = nullptr);

But this does not seem to set next and prev to nullptr when i create a new node_t.

    node_t(double d, node_t * n = nullptr, node_t * p = nullptr)
    {
        val = d;
        next = n;
        prev = p;
    }

This works however, but i fail to understand why the first way to don't work

mrmagin
  • 61
  • 1
  • 7
  • 1
    Please show a full [mcve]. Without seeing the full definition of the constructor, how you call it, and what problem you think you observe, we can't really help. – BoBTFish May 18 '18 at 10:25
  • 1
    The first version is a [declaration](http://en.cppreference.com/w/cpp/language/function#Function_declaration), the second is a [definition](http://en.cppreference.com/w/cpp/language/function#Function_definition). Thus, the first version will only introduce the name of the function, but will not define it. – gflegar May 18 '18 at 10:27
  • 1
    `next` and `prev` in the first code snippet are the formal parameter names of the `node_t` ctor args -- not the names of the associated class members. Is that where the confusion lies? – G.M. May 18 '18 at 10:31
  • What you probably wanted to use in the first version is a [member initializer list](http://en.cppreference.com/w/cpp/language/initializer_list): `node_t(double value, node_t * next = nullptr, node_t * prev = nullptr) : val{value}, next{next}, prev{prev} {}`. – gflegar May 18 '18 at 10:34
  • Note that to actually answer your question we would definitely need a MCVE as BoBTFish already mentioned. What we can do right now is only speculate what your actual problem may be. – gflegar May 18 '18 at 10:38

1 Answers1

0

This is just a specification of a function :

node_t(double value, node_t * next = nullptr, node_t * prev = nullptr);

A constructor initializing class variables should look like this :

node_t(double d, node_t * n = nullptr, node_t * p = nullptr)
    : val (d), 
    next (n), 
    prev (p) 
{}
Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31