title: How do I initialize a variable size array in a C++ class?
body: <p>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.</p>
  
  <p>I can define a constant and then work with that, as seen below:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #define ARRSIZE 5
  
  class Classy{
      private:
          int myarray[ARRSIZE];
  
      public:
          Classy();
          void printarray();
  };
  
  Classy::Classy(){
      for(int i = 0; i &lt; ARRSIZE; i++){
          myarray[i] = i * i * 2;
      }
  }
  
  void Classy::printarray(){
      for(int i = 0; i &lt; ARRSIZE; i++){
          std::cout &lt;&lt; myarray[i] &lt;&lt; std::endl;
      }
  }
  </code></pre>
  
  <p>However, I'd like to do it like this:</p>
  
  <pre><code>#include &lt;iostream&gt;
  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 &lt; arraysize; i++){
          myarray[i] = i * i * 2;
      }
  }
  
  void Classy::printarray(){
      for(int i = 0; i &lt; arraysize; i++){
          std::cout &lt;&lt; myarray[i] &lt;&lt; std::endl;
      }
  }
  </code></pre>
  
  <p>The compiler really doesn't like my approach though, so I am looking for an alternative way of doing things.</p>
  
  <p>I did some googling on the subject, but my searches did not come up fruitful. I found <a href="https://stackoverflow.com/questions/25153153/initializing-array-of-variable-size-inside-a-class">this</a> 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).</p>