Question

I have the following struct which I wanted to initialize

struct Box{
    int *dimval;
    int no;
    int dim;

    Box(dim){
        this->dim = dim;
        dimval = new int[dim]
    }

}

now in my main function. I wanted to initialize an array of Box struct, but this is problematic with my implementation.

int main(){
    Box *boxes;
    int num_box, dim;

    cin>>num_box>>dim;

    boxes = new Box[num_box](dim);// I know this is devil here. 
}

I want to have a dynamic array containing num_box Box items, each being initialized with a dynamic array of dim long. How can I do that?

Was it helpful?

Solution

You cannot create an array of a type unless it has a default constructor, and then you can't initialize each of them. However, you can initialize a vector with a default object, which is pretty much what you're asking for here.

#include <vector>

int num_box, dim;
cin >> num_box >> dim;
vector<Box> boxes(num_box, Box(dim));

Note that you need a copy constructor to handle the copying of dimval...

#include <algorithm>

struct Box
{
    // ...

    Box(const Box& that)
    {
        this->dim = that.dim;
        this->no = that.no;
        this->dimval = new int[dim];
        copy(that.dimval, that.dimval + that.dim, this->dimval);
    }
};

... but you can use the default copy constructor if you simply replace your dimval pointer with a vector, too, since vectors handle copy (that would fix a leak, too).

struct Box
{
    vector<int> dimval;
    int no;
    int dim;

    Box(int dim)
    : dimval(dim)
    {
        this->dim = dim;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top