It seems avr-gcc version 4.9.2 that is used by the Arduino IDE has been compiled without RTTI support. It defaults to -fno-rtti
, and if you try turning it on with -frtti
you just get other horrible linker error messages instead.
So it looks like you can't use dynamic_cast
on AVR boards.
Googling around it looks like numerous people have tried to enable FTTI on Arduino, but they have either failed and given up, or they have succeeded and never bothered to tell anyone else how they did it (numerous forum posts of "how do you do this?", a bit of discussion, and then they tail off...)
The solution? Either don't use RTTI, or use a more capable microcontroller whose compiler has RTTI enabled.
One way to not use RTTI is to fake it yourself:
#define CLASS_A 1
#define CLASS_B 2
class A {
public:
virtual int classType() { return CLASS_A; }
};
class B : public A {
public:
virtual int classType() { return CLASS_B; }
void bar() {
Serial.println("Baaaah!");
}
};
void foo(A *foo) {
if (foo->classType() == CLASS_B) {
B *foob = (B *)foo;
foob->bar();
} else {
Serial.println("Sorry, I can't bar.");
}
}
void setup() {
Serial.begin(115200);
A a;
B b;
foo(&a);
foo(&b);
}
void loop() {
}
Output:
Sorry, I can't bar.
Baaaah!