0

I have an array which I need to associate with an object. I need to define an array pointer in a class and declare it when the object is called. Is this a good practice or are there any better ways to do it.

FILE : header_name.h

class header_name{
public:
int **field_var;
void data_init(int rows,int cols);
};

FILE : header_name.cpp

#include "header_name.h"
void header_name::data_init(int rows,int cols){
field_var=new int *[rows];
for(int i=0;i<rows;i++){
   field_var[i]=new int[cols];
}
for(int i=0;i<rows;i++){
   for(int j=0;j<cols;i++){
      field_var[i][j]=0;
   }
}
}

Thanks for the help

Some_Guy
  • 169
  • 11
  • 6
    The c++ way is use standard containers and not do this using pointers at all. However I assume this is an assignment. – drescherjm Dec 17 '17 at 19:25
  • 1
    Please utuilize a vector – Jake Freeman Dec 17 '17 at 19:25
  • [The best way is not to use pointers at all](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr). – user0042 Dec 17 '17 at 19:26
  • ok, in case i use vectors, still is it ok to declare them in the class and then start allocating/appending them through the object function? – Some_Guy Dec 17 '17 at 19:29
  • Yes you can do that. – drescherjm Dec 17 '17 at 19:33
  • If for some inevitable reasons you have to manage the dynamic data in the array pointer on your own, you must remember the big 3 rules / 5 rules(move semantics). Or you will get serious trouble when assigning/copying/moving this class. – Chen OT Dec 18 '17 at 09:01

0 Answers0