0

I've got a tricky issue with "overriding" static arrays. I've got static arrays (for simplicity) that are of fixed length in different derived classes, but still all sizes are known in compile-time. I've also got a virtual function in the base class, but I don't know how to tackle the problem of overriding these arrays and array-sizes in the derived classes so that this virtual function works correctly, i.e. gives the sizes and array contents from the derived classes. Example:

class B  {
private:
 // these two are not really meaningful in this class (ABC)
 static const int n = 1;
 static double da[n];
public:

 virtual void f()
 {
  for(int i = 0; i < n; ++i)
  {
   // do something with n and da
   std::cout << n << std::endl;
  }
 }
};

class D1 : public B  {
private:
 // these are subclass-specific (i.e. n might also change)
 static const int n = 4;
 static double da[n];
};

class D2 : public B  {
private:
 // these are subclass-specific (i.e. n might also change)
 static const int n = 6;
 static double da[n];
};


double D1::da[] = {1., 2., 3., 4.};
// ...

int main()
{
 B *p = new D;
 p->f(); // I'd like to see 4 instead of 1
}

Could you suggest a fix or a different way of doing this correctly? I think std::vector would do it (?), but needs much work to adapt to my existing code. Many thanks, Peter

Peter
  • 515
  • 1
  • 5
  • 8

2 Answers2

1

Since f is only defined in the Base class, it will use that class' n variable.

Perhaps move:

for(int i = 0; i < n; ++i) 
  { 
   // do something with n and da 
   std::cout << n << std::endl; 
  }

To a separate function, but instead have it so you pass in what "n" is. like

void doStuff(int num) {
    for(int i = 0; i < num; ++i) 
    { 
      // do something with n and da 
      std::cout << num << std::endl; 
    }
}

And have each subclass implement f() to call doStuff(n) where n will be each class' own n variable.

robev
  • 1,909
  • 3
  • 23
  • 32
1

You could use the Curiously Recurring Template Pattern to make your function access the static array in the most-derived class.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Many thanks, I tried this as you've suggested and it works as expected. Unfortunately, I want to be able to use dynamic polymorphism over the B interface which I think is not possible by this way. Or is it? – Peter Nov 13 '10 at 22:14