Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit an array that is initialised in the child

I'm looking for the best way to do something like this:

class variable{
    protected:
    variable()
    int convert[][]
}

class weight: variable{
    public:
    weight(){
        convert = {{1,2},{1,3},{2,5}}
    }

Now I know I can't do this as I have to declare the array size in advance. I have many classes all inheriting from base class variable, and variable has a function using convert so don't want to declare convert in each one separately. For each class the array length will stay constant so using a list seems unnecessary. What are your suggestions.

Many thanks.

like image 462
wookie1 Avatar asked Oct 10 '22 12:10

wookie1


1 Answers

There are several options.

  • Use std::vector.
  • Or use std::array (available in C++11 only)
  • Or do something like this:

    template<size_t M, size_t N>
    class variable{
       protected:
         int convert[M][N];
    };
    
    class weight: variable<3,2>{
    public:.
     weight(){
       //convert = {{1,2},{1,3},{2,5}} //you cannot do this for arrays
       //but you can do this:
       int temp[3][2] = {{1,2},{1,3},{2,5}};
       std::copy(&temp[0][0], &temp[0][0] + (3*2), &convert[0][0]);
    };
    
  • Or you can use std::vector or std::array along with template as well.

like image 136
Nawaz Avatar answered Oct 12 '22 23:10

Nawaz