How can I instantiate a class with statically declared arrays of different sizes?

I'd like to create a class with a statically declared array. I'd like to extend the class that basically changes the size of the array in the derived class. Everything else would stay the same.

namespace someNameSpace {
   const uint8_t STATIC_ARRAY_SIZE = 50; // <-- change this value in a derived class?
   class BaseClass {
       private:
          int some_array[STATIC_ARRAY_SIZE];
       public:
          void some_function_that_uses_above_array(){ ... };
   }
}

Is there a way to do this without using templating? (I need the arrays to be allocated memory at compile time).

2 answers

  • answered 2019-08-19 02:46 sturcotte06

    You can use template meta-programming for this:

    namespace someNameSpace {
        template <size_t STATIC_ARRAY_SIZE>
        class BaseClass {
        private:
            int some_array[STATIC_ARRAY_SIZE];
        public:
            void some_function_that_uses_above_array(){ ... };
        }
    
        class Derived : public BaseClass<42> {
            ...
        }
    }
    

  • answered 2019-08-19 03:55 Marcos Vinicius De Souza

    If you want to allocated at compile time, it is mean not dinamically allocated i think the solution you want still is template. At compile time for each different template parameter the compiler will generate a copy of class.

    Example:

    With @sturcotte06 code, if you declare in someplace BaseClass<10> or BaseClass<20>, for each parameter 10 and 20, the compiler will copy the code of class and apply the parameter like a #define. In this link search for "PrintTwice function with int and double", there is a pratical example.

    If you can't use template because of restrictions, i don't recommend but you can pass the array through constructor as a smart pointer, to avoid null reference is important check pointer on costructor and take a care on destructor.