4

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?

José María
  • 2,835
  • 5
  • 27
  • 42
  • That approach shows some trouble. Based on your previous tags, [choose one of those](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Zeta Dec 29 '15 at 11:40

4 Answers4

3

Use a std::vector:

class CharacterSequence
{
private:
    std::vector<char> _sequence;

public:
    CharacterSequence(int size) : _sequence(size)
    {
    }
}; // eo class CharacterSequence
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
2

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;
KarenRei
  • 589
  • 6
  • 13
  • Also note that if you want sequence to be iterable, instead of a char array you can use a std::array. Then all of the stl container functions will work with it, and it should make little to no performance difference with optimization turned on, and in some cases can even be faster. – KarenRei Dec 29 '15 at 12:07
1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • std:.array cannot be set on construction - it's std::array - the size is a template parameter. Perhaps you're thinking of std::list? It should be pointed out to the user that std::vector is generally faster, but std::list can be faster if one is doing a lot of deletion operations. – KarenRei Dec 29 '15 at 12:02
  • Oops. Better dust off that Stroustrup. Thanks for the reminder ;-) – Bathsheba Dec 29 '15 at 12:03
1

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;
};
Shivakumar
  • 427
  • 2
  • 15