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.

4
  • What board are you trying to compile for?
    – Majenko
    Aug 9, 2018 at 17:29
  • Arduino Mega2560 Aug 9, 2018 at 17:58
  • What IDE version and boards package version do you have?
    – Majenko
    Aug 9, 2018 at 17:59
  • PlatformIO and arduino-1.8.5 Aug 9, 2018 at 18:29

1 Answer 1

2

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!
1
  • You gave a band-aid solution. It is already valid. Aug 9, 2018 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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