I have an array as a member of a class. In a subclass, I would like to re-define the array with a different size. I want to do this because I anticipate making many subclasses, each with only the array size it needs, and nothing more.
class Foo
{
Foo() {ivar = 1};
int thisArray[2];
int ivar;
}
class Bar : public Foo
{
Bar() {ivar = 3};
int thisArray[4];
}
int main()
{
Foo myFoo;
Bar myBar;
Foo fooCollection[] = {myFoo,myBar};
cout << "myFoo array size = " << sizeof(myFoo.thisArray)/sizeof(int) << endl;
cout << "myBar array size = " << sizeof(myBar.thisArray)/sizeof(int) << endl;
for (int n=0;n<2;n++)
{
cout << "fooCollection[" << n << "] array size = ";
cout << sizeof(fooCollection[n].thisArray)/sizeof(int) << endl;
}
for (int n=0;n<2;n++)
{
cout << "fooCollection[" << n << "] ivar = ";
cout << fooCollection[n].ivar << endl;
}
}
My results are:
myFoo array size = 2
myBar array size = 4
fooCollection[0] array size = 2
fooCollection[1] array size = 2
fooCollection[0] ivar = 1
fooCollection[1] ivar = 3
I get that, since I declare the array objects as objects of class Foo, that referring to myBar within that scope would reference myBar as though it was a Foo and consequently interpret the size of thisArray as equivalent to 2. I also understand why ivar comes out the way it does.
Is there a way to affect the size of thisArray within the Bar class so its “correct” size can be recognized within an array of Foo objects? I would use a vector, but they are not friendly on the arduino platform. I could also simply make the array within the Foo class with a size of 100, but I am trying to be conscious of memory allocation.
When you do this:
cout << sizeof(fooCollection[n].thisArray)/sizeof(int) << endl;, it is impossible to know the size ofthisArraybecause you are not using actual polymorphism. So the compiler assumes all elements infooCollectionare simpyFoo(static binding).Start by using pointers:
And declaring a virtual member that will know at runtime the size of the array. (dynamic binding)
And then rewriting to: