C ++: dynamic memory allocation and class constructors

advertisements

I believe that I may be either misusing OOP or doing something wrong with my memory allocation in class constructors.

I will illustrate what I am doing with a simplified example:

class data
{
    data(int n) : m_data(new double[n])
    {
    }

    virtual ~data()
    {
        delete [] m_data;
    }

    double min() { ... }
    double max();
    double mean(); // return minimum, maximum and mean values

    double *m_data;
}

class dual_data : public data
{
    dual_data(int n) : m_data(new double[2*n])
    {
    }
}

I believe this will cause a disastrous memory leak. (It should be clear why, as one constructor allocates memory before the other then overwrites the pointer with another call to new.)

In case it isn't already clear, I have 2 classes: One is a class similar to std::vector which handles data storage in memory for me, and the other is a derived class which does the same thing, but expects data in the format of x,y pairs rather than individual values. The reason for this is that x,y pairs can be processed in different ways than to just a vector. For example, with statistical data processing to compute correlations or something else entirely. But it is still useful to be able to call the functions min(), max() and mean() in the class dual_data, which are inherited from data.

What should I do to correct for the memory leak?


Maybe this should do: you tell the base class to allocate an array of 2*n elements. Besides the base class is responsible for freeing the memory. No destructor needed.

class dual_data : public data
{
    dual_data(int n) : data(2*n)
    {
    }
}