Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C++, how can I use a constructor to initialize a structure that is already declared?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    {
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading