Reputation: 1883
I'm attempting to create my own double linked list for learning experience. My book showed the node struct below and I was wondering is that equivalent to my Node class I created? Is that function in the struct just a type of constructor assigning values to each data type in the struct?
//===== Struct =====
struct Node
{
Node *next;
Node *prev;
std::string val;
Node(const std::string &value, Node *nextVal = NULL, Node *prevVal = NULL) :
val(value), next(nextVal), prev(prevVal) {}
};
//===== Class ====
class Node
{
public:
Node(std::string value = "", Node *pVal = NULL, Node *nVal = NULL);
virtual ~Node(void);
protected:
Node *next;
Node *prev;
std::string val;
};
Node(std::string value = "", Node *pVal = NULL, Node *nVal = NULL)
{
next = nVal;
prev = pVal;
val = value;
}
Upvotes: 3
Views: 3735
Reputation: 6812
This is called a constructor initializer list and it is meant to initialize the attributes of a struct or a class.
This is usually the preferred way of initializing attributes. here's a discussion explaining why:
Is it possible to defer member initialization to the constructor body?
Long story short, if you don't explicitly initialize an attribute in the initializer list, it is initialized implicitly using the default constructor and therefor, you will be initializing the variable twice.
Also, you need accessors for your pointer.
class Node
{
public:
Node():next(NULL),prev(NULL),val("") {};
Node(std::string value):next(NULL),prev(NULL),val(value) {};
Node(std::string value, Node *pVal):next(NULL),prev(pVal),val(value) {};
Node(std::string value, Node *pVal, Node *nVal):next(nVal),prev(pVal),val(value) {};
virtual ~Node(void);
std::string getValue()
{
return val;
}
void setValue(std::string v)
{
val = v;
}
Node * getNext()
{
return next;
}
void setNext(Node * n)
{
next = n;
}
Node * getPrevious()
{
return prev;
}
void setPrevious(Node * n)
{
prev= n;
}
protected:
Node *next;
Node *prev;
std::string val;
};
Upvotes: 1
Reputation: 176
Yes - that's exactly what it is.
Here's a page with an example of a struct constructor.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++Structures.html
Upvotes: 1