I have a problem with using class, subclass, and associated constructors.
When instantiating a subclass, I want to modify the value of a variable of a class.
In my example, the main class (Top) contains a public variable topVal initialized by default to 0xFFFFFFFF. In the constructor of the subclass (Sub), I want to reassign this variable to a new value 0x55AA00FF, but it doesn't work. On the other hand, the variable tstVal is well updated in the constructor of the subclass.
Here is the code used:
// This test runs on a Seeeduino XIAO card
#ifdef SERIAL
#undef SERIAL
#endif
#define SERIAL SerialUSB
// Class declaration
class Top
{
public:
Top();
uint32_t topVal = -1;
};
class Sub : public Top
{
public:
Sub(uint32_t test);
uint32_t subVal = 0x55AA00FF;
uint32_t tstVal = 0;
};
// Instantiation of classes
Top top;
Sub sub(0x12345678);
// Builders
Top::Top()
{
}
Sub::Sub(uint32_t test)
{
this->tstVal = test;
this->topVal = this->subVal; // Not executed ?!?
}
// Application
void setup()
{
SERIAL.begin(115200);
while(!SERIAL);
SERIAL.print(F("topVal = "));
SERIAL.println(top.topVal, HEX);
// Should display : topVal = 55AA00FF
// But display : topVal = FFFFFFFF
SERIAL.print(F("subVal = "));
SERIAL.println(sub.subVal, HEX);
// Display : subVal = 55AA00FF
SERIAL.print(F("tstVal = "));
SERIAL.println(sub.tstVal, HEX);
// Display : tstVal = 12345678
}
void loop()
{
}
the Top class has one instance variable, topVal
so when you instantiate Top top; you get such a variable
The Sub class inherits from Top, so any Sub instance also has a topVal variable that has its own life.
Since this topVal is not a class variable, they are fully independent and the topVal variable from the top instance is not the same as the topVal variable from the sub instance.
All makes sense to me
if you want a shared class variable, declare the Top class as such
class Top {
public:
static uint32_t topVal; // a class variable
};
uint32_t Top::topVal = -1; // allocation of the memory for the class variable
describe what you want to achieve: do you want to have separate values of .topVal for each instance (than you have to modify the top.topVal if it should become modified) or something like one common value for all instances (including for instances of inherited classes) --> static.
'top' is a separate object and your declaration of 'sub' has nothing to do with it. If you want to see if your initialization of 'sub' went as expected: