0

I'm trying to define a bunch of structs in a header file. For example:

struct Firststruct{
    int useless;
};

struct Secondstruct{
    Firststruct* struct1;    // we want to have a dynamic array here.    
};

struct Thirdstruct{
    Secondstruct* struct2;    // we want to have a dynamic array here.    
};

And for simple usage in main or source file. We want to define the struct constructor. For example:

struct Secondstruct{
    Firststruct* struct1;    // we want to have a dynamic array here. 

    // constructor
    Secondstruct(int num_struct1){
        struct1 = new Firststruct[num_struct1];
    };

    // deconstructor
    blablabla
};

So here is the question, how could we define the constructor in Thridstruct?

struct Thirdstruct{
    Secondstruct* struct2;    // we want to have a dynamic array here. 

    // constructor
    Thirdstruct(int num_struct2){
        struct2 = new Secondstruct[num_struct2];    // this of couse does not work. 
    };

    // deconstructor
    blablabla
};

I am new in C++, so I do not know how to write it. Could someone provide some ideas?

Thanks. :)

3

1 Answer 1

3

Option 1: make Secondstruct default constructible by defining a default constructor.

Option 2: do not create a dynamic array of Secondstruct directly, but instead a dynamic array of raw bytes of sufficient size. Then reuse the storage with std::uninitialized_fill.

Best option: Use std::vector instead which does the complicated sounding thing of option 2 as well as lacks the memory leaks and undefined behaviour that the custom attempt of implementing dynamic array is undoubtedly going to suffer from.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.