How to initialize dynamic array inside a class in cpp?

by Bidesh Sengupta   Last Updated May 16, 2019 00:26 AM

I wish to initialize an multidimensional dynamic array inside a class. But I am getting error.

I have seen several examples in net. They seem to be difficult. I am new to coding. I wish simple solution if possible.

class myp
{
    int ntc = 5;
    public:
    double** y = new double*[ntc];
    for(int i = 0; i < ntc; ++i)
        y[i] = new int[3];
};
int main()
{
    int x;
    myp mp;
    mp.y[1][1] = 3;
    cout<<mp.y[1][1]<<endl;;
    //cout<<"gandu"<<endl;
    return 0;
}

test.cpp:12:2: error: expected unqualified-id before ‘for’
  for(int i = 0; i < ntc; i++)
  ^~~
test.cpp:12:17: error: ‘i’ does not name a type
  for(int i = 0; i < ntc; i++)
             ^
test.cpp:12:26: error: ‘i’ does not name a type
  for(int i = 0; i < ntc; i++)


Answers 1


You need to do class initialisation in the constructor function, and cleanup in the destructor.

class myp
{
  int ntc = 5;
public:
  double** y;

  // constructor
  myp()
  {
    y = new double*[ntc];

    for(int i = 0; i < ntc; ++i)
      y[i] = new int[3];
  }

  // destructor
  ~myp()
  {
    for(int i = 0; i < ntc; ++i)
      delete [] y[i];
    delete [] y;
  }

  // be careful of the copy ctor. I'm deleting it in this case!
  myp(const myp&) = delete;

};
robthebloke
robthebloke
May 16, 2019 00:25 AM

Related Questions


Updated April 22, 2015 01:11 AM

Updated July 19, 2017 00:26 AM

Updated August 18, 2017 00:26 AM

Updated January 14, 2018 10:26 AM

Updated June 14, 2015 01:11 AM