I need to make a class that has an array as a data member. However I would like to make it so that the user can choose the size of the array when an object of that class is created. This doesn't work:
class CharacterSequence {
private:
static int size;
char sequence[size];
public:
CharacterSequence(int s) {
size = s;
}
};
How would I do this?
Use a std::vector:
class CharacterSequence
{
private:
std::vector<char> _sequence;
public:
CharacterSequence(int size) : _sequence(size)
{
}
}; // eo class CharacterSequence
Others have suggested using a std::vector... but I don't think that's what you really want. I think you want a template:
template <int Size>
class CharacterSequence {
private:
char sequence[Size];
public:
CharacterSequence() {
}
};
You can then instantiate it to whatever size you want, such as:
CharacterSequence<50> my_sequence;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With