Hi!
I want to extend a base class into different objects. Is there a way to put this different objects into one array?
I'm new to Arduino and OOP and so I'm not sure wether this makes sense and how to get it done.
If I declare and array of the BaseClass type I cannot access the functions from the extended classes. But if I declare the array as ExtendedClass I'm not able to put other variants into that array. e.G. ExtendedClass2.
The idea was to build a stack to do different things. All stack objects are extended from the same base class. But perhaps this is complete nonsense:
I would use an array of base class pointers and virtual functions for the common behaviour,
like @wildbill suggested already, if I wanted to have a list of different objects.
#include <memory>
class BaseClass {
public:
BaseClass() = default;
virtual void hello() const {
Serial.println("BaseClass");
}
};
class ExtendedClass : public BaseClass {
public:
ExtendedClass() = default;
void hello() const override {
Serial.println("ExtendedClass");
}
};
std::unique_ptr<BaseClass> arrBaseClass[10];
int main() {
arrBaseClass[0] = std::unique_ptr<ExtendedClass>(new ExtendedClass());
// If you have access to C++14 (e.g. on Teensy) use std::make_unique instead:
arrBaseClass[1] = std::make_unique<ExtendedClass>();
arrBaseClass[2] = std::make_unique<BaseClass>();
arrBaseClass[0]->hello(); // ExtendedClass
arrBaseClass[1]->hello(); // ExtendedClass
arrBaseClass[2]->hello(); // BaseClass
}
This requires the standard library.
Note that the hello method is marked virtual in the base class and override in the child class.
Don't define empty constructors, either mark them = default or don't define them at all.
If you provide storage for the objects in the array elsewhere, you could use an array of raw pointers.
I would recommend an array of base class pointers. Then if you want to access the derived class function using a base class pointer you simply cast the pointer to the derived class.
If you don't ever have the need, or want to prevent the base class from being instantiated then use a pure virtual function which will make the class abstract.