I am writing a program using the Arduino environment and the ChRt library https://github.com/greiman/ChRt, developing for the Teensy MicroMod.
As you may know, the Arduino environment allows for programming in C++, so this is the language that I'm using. I am implementing a dynamic list of objects derived from a common base class. I have a helper function to append items to the list. The base class features a pure virtual function that must be overridden by all subclasses. The code looks something like this:
Code: Select all
class Base {
public:
Base *next = NULL;
Base *prev = NULL;
virtual void doWork() = 0;
};
class Child1 : public Base {
public:
void doWork() { /* Child1 version of doWork() */ };
};
class Child2 : public Base {
public:
void doWork() { /* Child2 version of doWork() */ };
};
Base *head = NULL;
Base *tail = NULL;
void append(Base *p) {
if (head == NULL) {
head = p;
tail = p;
}
else {
tail->next = p;
p->prev = tail;
tail = p;
}
}
void main() {
Child1 *c = (Child1 *)chHeapAlloc(NULL, sizeof(Child1));
append(c);
head->doWork(); /*Segmentation fault*/
}
As I mentioned in the code comment, calling the doWork function on an element of the list (here called on "head" for simplicity) gives a segmentation fault. The interesting thing is that if I skip explicitly instantiating c and instead I do
Code: Select all
append(new Child1());
the program runs no problem, the Child1 version of doWork is correctly called. So I have the suspicion that somehow, chHeapAlloc breaks polymorphism in some way. I could also be way off and any C++ advice would be welcome
Thank you all in advance for your help