Gengis
Gengis

Reputation: 63

How can I redefine array size in a subclass?

I have a base class in which I define an array of structs (of base types) and some methods that act on its objects; I never instantiate directly this class, just created varius sublasses of it. Now, in each subclass I would like to redefine the array size to the subclass particular needs.

Consider that I would like to avoid dynamic allocation in order to keep the program more dependable and because I like to see at compile time the amount of memory I'm using with my design.

I tryed by simply redefining the array in the subclasses; the compiler (I use Arduino IDE) does not complain about it but, from the amount of memory used reported by the compiler, I see that actually both arrays exist (the one defined in base class and the one "redefined" in the subclass) so it seems this is not the way to do it.

I found a suggestion about using templates but It hasn't received much approval, and because I read that templates are about making a class manage different data types, I think my problem of wanting just a different array size could have a more simple solution.

What is the correct way to obtain what I want?

Here is an example of my (wrong) code:

typedef struct {
    char val1;
    int val2;
} DataItem;


class BaseClass {
    DataItem dataItems[5];
};

class Sublass_A : public BaseClass {
    DataItem dataItems[50];
};

class Sublass_B : public BaseClass {
    DataItem dataItems[15];
};

Upvotes: 0

Views: 207

Answers (2)

Gengis
Gengis

Reputation: 63

Here is the initial code of my question, corrected following the @Jarod42's answer.

typedef struct {
    char val1;
    int val2;
} DataItem;


template <size_t N = 5> // 5 is the default value if the size is not specified
class BaseClass {
    DataItem dataItems[N];
};

class Sublass_A : public BaseClass<50> {
};

class Sublass_B : public BaseClass<15> {
};

It compiles correctly and tests using sizeof() on the subclasses objects reported the expected sizes of the array.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217085

With template, you might do something like:

template <std::size_t N>
class ItemsArray {
    DataItem dataItems[N];
};

using classA = ItemsArray<50>;
using classA = ItemsArray<15>;

Upvotes: 1

Related Questions