Is it possible?
If I derive a class, then override one method, is there a way for the base class to use this method?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Base{
void writebyte(){};
void display(){ writebyte()};
};
class Derived : public Base {
void writebyte(){};
};
int main {
Derived a;
a->display(); //--> Is it possible to make the base method display use the derived method writebyte?
};
The solution I am finding so far is that I have to copy the base method display into the derived class and then it will use the derived class writebyte method. I have no control over the base class and the methods are not virtual.
What you're describing is runtime polymorphism. As you have it now, your Dervied class's writebyte function is shadowing the Base class's function. For proper polymorphism, you need virtual functions. I suggest reading more into C++ polymorphism yourself.
The term "override" necessarily implies the use of virtual functions.
For the particular use case in your first post, I believe you could actually use the curiously recurring template pattern (CRTP), which is also known as a form of "static polymorphism". This would avoid virtual functions, but still requires modifying the base class.
Or you could have writebyte be a function pointer that the derived class assigns to. Still would require modifying the Base class. (This is basically just reimplementing virtual functions.)
I don't see a way to make the Base class's display() function call the Derived class's writebyte() function without modifying the Base class. Perhaps this is an XY problem and you should explain why you can't modify Base, or what the code as a whole is trying to do. If this is some existing code you are maintaining and can't modify it, then duplicating the display function seems like your best option. At which point, the need for inheritance itself is questionable.
It's a publicly available arduino library called TM1637_6D. I derived a class from it and added some more methods but I also rewrote the writebyte function for faster IO.
Initially I did not consider rewriting the writebyte function so it made sense to derive a class as I used a lot of the base methods. Then I came across DirectIO.
Now, it seems like most of the code that called writebyte() had to be copied over to derived in order to use derived writebyte().