Hi there!
Im trying to implement a technique I learned from other languages. Im want to use a generic parent class to call overwritten (virtual) methods from children classes. Currently Im failing allready when trying to gather the classes in an array (simplyfied version):
#include "i2CScreenScan.h"
i2CScreenScan screenScan(tft,0);
SCTFTScreen * screens[1];
void setup()
{
screens[0] = screenScan;
}
But I get an error saying:
exit status 1
cannot convert 'i2CScreenScan' to 'SCTFTScreen*' in assignment
"i2CScreenScan" inherits from "SCTFTScreen" so it is actually a "SCTFTScreen". I want to call a generic virtual function "draw()" on this object later in code by looping over the objects in the array:
void drawScreens()
{
for(int i=0;i<numScreens;i++)
{
SCTFTScreen * s = screens[i];
if(s.index == activeScreen)
{
s.draw();
}
}
}
The inheritance is working so far when Im not trying to cast to the parent class.
Is this possible in C++?
Thank you very much for help!
Got it myself. Its simple casting to the object. Sorry.
In case anybody struggling with downcasting too:
screens[0] = (SCTFTScreen *) screenScan;
// upcast - implicit type cast allowed
Parent *pParent = child;
// downcast - explicit type case required
Child *pChild = (Child *) parent;
Got the example and the infos from this site: C++ Tutorial: Upcasting and Downcasting - 2020
Thanks anyway!
asuryan:
i2CScreenScan screenScan(tft,0);
SCTFTScreen * screens[1];
screens[0] = (SCTFTScreen *) screenScan;
This won't work. You're trying to assign an variable of type i2CScreenScan to a variable of type pointer to SCTFTScreen.
You are forcing the compiler to convert it anyway, using a C-style cast. You shouldn't use this in C++, use static_cast
instead (it won't solve your problem here, but it'll only allow valid casts).
When you use the correct types, up-casting is implicit in C++:
i2CScreenScan screenScan;
SCTFTScreen *screens[1];
screens[0] = &screenScan;
Note the address-of operator used to get a pointer to screenScan
.
Pieter
I see!
Thank you very much for your help!