Reputation: 3053
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?
Upvotes: 4
Views: 1698
Reputation: 477
Determining the size of an array during run time is nothing but allocating memory at run time. But size of the array has to be determined during compile time. Hence you cannot follow the method you mentioned above.
Alternatively, you can create a pointer and allocate memory at run time i.e. you can assign the size of your wish when you create object as below:
class CharacterSequence {
private:
static int size;
char *sequence;
public:
CharacterSequence(int s) {
size = s;
sequence = new char[size];
}
~CharacterSequence(){
delete []sequence;
};
Upvotes: 1
Reputation: 609
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;
Upvotes: 2
Reputation: 234645
You can't. Variable length arrays are not supported by C++.
Why not use a std::vector<char>
instead? Its size can be set on construction.
Upvotes: 1
Reputation: 38825
Use a std::vector
:
class CharacterSequence
{
private:
std::vector<char> _sequence;
public:
CharacterSequence(int size) : _sequence(size)
{
}
}; // eo class CharacterSequence
Upvotes: 3