0
class A {
    virtual ~A();
}

class B : public A {
    public:
      int foo;
}

void bar(A *foo_){
    B* b = dynamic_cast<B*>(foo_);

    if(b != nullptr){
         cout << (*foo_)->foo << endl;
    }
}

int main(){
    B b{};
    bar(b);
}

Compiling error:

error: 'dynamic_cast' not permitted with -fno-rtti

I thank sincerely for the help.

1

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.