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?

1
  • That approach shows some trouble. Based on your previous tags, choose one of those. Commented Dec 29, 2015 at 11:40

4 Answers 4

3

Use a std::vector:

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

public:
    CharacterSequence(int size) : _sequence(size)
    {
    }
}; // eo class CharacterSequence
Sign up to request clarification or add additional context in comments.

Comments

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;

1 Comment

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.
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.

2 Comments

std:.array cannot be set on construction - it's std::array<class, std::size_t> - 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.
Oops. Better dust off that Stroustrup. Thanks for the reminder ;-)
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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.