I have a class that needs to store an array with a variable size. Ideally, this size would be defined as a parameter given to the constructor of the class.
I can define a constant and then work with that, as seen 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'd like to do it like this:
#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 though, so I am looking for an alternative way of doing things.
I did some googling on the subject, but my searches did not come up fruitful. I found this approach which does it using dynamic memory allocation. This is something I'd like to avoid, so I am looking for a solution that does not rely on that. It might well be (and I'm starting to think) that it is the only elegant solution to my problem (and if this is the case, the question should of course be closed as duplicate).