[Solved] Confused on purpose/meaning of code in C++ struct declaration


The member function that you have defined (node(...)) is a constructor and lets the compiler know what to do when you create an object on type node. For example, in your code, you use this statement in your push function: t = new node(a, t);. Compiler has to know how to create a new node with the two arguments passed to it.

In your constructor you need to initialize the class members. Something like:

node(const T &newvalue, node *nextnode)
{
    value = newvalue;
    next = nextnode;
}

But when the compiler uses this on the line node(a, t), it is going to default-initialize value and next first, then assign the correct values inside the constructor. Using the constructor initializing list lets the compiler initialize those members the first time. It can be a means to improve performance if objects of type T are expensive to construct. There are other benefits that you gain by using constructor initializing list and you’ll probably come across them as you learn more about C++.

solved Confused on purpose/meaning of code in C++ struct declaration