How to allocate an array in a base constructor with a size based on a derived class?

I have a class hierarchy. The base class uses some settings that can be loaded from a file (and reloaded at runtime). Each derived class may add some additional parameters. I am looking for a way to allocate an array of parameters with the correct size in the base constructor, so that I do not need to free and redistribute in the derived class. I was hoping for something like this, but it does not work (parameters always have 2 elements):

   class Base
   { static int nParms;
     virtual int getNParms() { return nParms;}
     float *parameters;
   public:
     Base() 
     { parameters= new float[this->getNParms()];
       parameters[0] = globalReloadableX;
       parameters[1] = globalReloadableY;
     }
   };
   int Base::nParams =2;

   class Derived : public Base
   { static int nParms;
     virtual int getNParms() { return nParms;}
   public:
     Derived() : Base()
     { parameters[2] = globalReloadableZ;
     }
   }
   int Derived::nParams =3;

I saw this question , but the solution there does not work for me. I also tried making the parameters a regular array in each class:

  class Base
  {  float parameters[2]
    ...
  class Derived : public Base
  {  float parameters[3]
    ...

but Derived has 2 separate arrays.

Any ideas?

+5
6

?

(, , , ++; , , , - .)

+5

?

class Base
{ static int nParms;
  virtual int getNParms() { return nParms;}
  float *parameters;
public:
  Base(int n = nParams) 
  { parameters= new float[n];
    parameters[0] = globalRelodableX;
    parameters[1] = globalRelodableY;
  }
};
int Base::nParams =2;

class Derived : public Base
{ static int nParms;
  virtual int getNParms() { return nParms;}
public:
  Derived() : Base(nParams)
  { parameters[2] = globalRelodableZ;
  }
}
int Derived::nParams =3;
+2

? std::vector , , ( ) , .

+2

, , Base- . , :

template <size_t nParams>
class Base
{
    float parameters[nParams];
public:
    Base()
    { // could use a static_assert(nParams > 1) here...
      parameters[0] = globalRelodableX;
      parameters[1] = globalRelodableY;
    }
};

class Derived : public Base<3>  // or whatever
{
public:
    Derived()
    { parameters[2] = globalRelodableZ; }
};
+2

std:: map. , . , "/" , .

0

, , , . , , , , , Earwicker . , , " ", , , , , , , , - .

0

All Articles