I have a class that should store a variable-sized array. Ideally, this size will be defined as the parameter specified by the class constructor.
I can define a constant and then work with it, as shown below:
#include <iostream> #define ARRSIZE 5 class Classy{ private: int myarray[ARRSIZE]; public: Classy(); void printarray(); }; Classy::Classy(){ for(int i = 0; i < ARRSIZE; i++){ myarray[i] = i * i * 2; } } void Classy::printarray(){ for(int i = 0; i < ARRSIZE; i++){ std::cout << myarray[i] << std::endl; } }
However, I would like to do it as follows:
#include <iostream> class Classy{ private: int arraysize; int myarray[arraysize]; public: Classy(int parraysize); void printarray(); }; Classy::Classy(int parraysize){ arraysize = parraysize; for(int i = 0; i < arraysize; i++){ myarray[i] = i * i * 2; } } void Classy::printarray(){ for(int i = 0; i < arraysize; i++){ std::cout << myarray[i] << std::endl; } }
The compiler really doesn't like my approach, so I'm looking for an alternative way to do something.
I did some searches on this, but my searches did not return any results. I found this approach that uses dynamic memory allocation. I would like to avoid this, so I am looking for a solution that does not rely on this. Maybe (and I'm starting to think) that this is the only elegant solution to my problem (and if so, the question, of course, should be closed as a duplicate).
source share