Suppose I have one structure called LinkedList:
struct LinkedList
{
private:
int curNode;
public:
node* head, * tail;
LinkedList()
{
curNode = 0;
head = NULL;
tail = NULL;
}
LinkedList(int val)
{
curNode = 1;
node* element = (node*)malloc(sizeof(node));
element->next = element->prev = NULL;
element->value = val;
head = tail = element;
}
};
Now, I have one more structure called Stack. It is not inheriting Linked List:
struct stack
{
private:
LinkedList model;
public:
stack()
{
//problem
}
stack(int value)
{
//problem
}
};
I have been searching thoroughly through the C++ documentation but I can not find the solution to my problem.
Here is the problem which I seek to solve:
Inside of the constructors, stack() and stack(int value), I want to initialize the LinkedList model, by using the constructors in my LinkedList struct. Can someone please explain to me what I would have to put in the areas in which I temporarily put the comments //problem?
>Solution :
You need to use a member initialization list to call constructors on class data members, eg:
struct stack
{
private:
LinkedList model;
public:
stack() : model()
{
}
stack(int value) : model(value)
{
}
};
In the case of the default constructor, it is optional to call it explicitly, as the compiler will automatically default-construct any data member that is not explicitly stated in the initialization list:
struct stack
{
private:
LinkedList model;
public:
stack() // : model() // <- you can omit this one
{
}
stack(int value) : model(value)
{
}
};