thomasfermi
thomasfermi

Reputation: 1243

class has class with dynamic array member

I have a class with a dynamic array (DA)

class DA{
  private:
    double* array;
    int size N;
    //other stuff
  public:
    DA(){
       array=NULL;
    }
    DA(int PN){
      N=PN;
      array=new double[N];
    };
    //destructor and other stuff
}

This seems to be ok. Now I want a class "Application" that has one DA object:

class App{
  private:
    DA myDA;
  public:
    App(int N){
      //create myDA with array of size N
      DA temp(N);
      myDA=temp;
    };
}

The problem is, that I don't know how to create myDA in the App constructor. The way I do it, memory is allocated for temp, then myDA points to temp. But I guess the memory allocated for temp is deleted after the constructor finishes. Hence, I get a memory error when I execute my program. So how do I allocate memory correctly?

Upvotes: 2

Views: 221

Answers (1)

juanchopanza
juanchopanza

Reputation: 227608

Using a constructor initialization list:

App(int N) : myDA(N) {}

Note that your DA class is broken unless you follow the rule of three, or simplify the problem by using an std::vector<double>, an std::unique_ptr<double[]> or a boost scoped array:

#include <vector>

class DA{
  private:
    std::vector<double> data; // "array" is a std lib container name
  public:
    DA(int PN) : data(PN) {}
    // no need to write destructor, copy constructor or assignment operator.
};

Upvotes: 7

Related Questions