0

I am trying to understand how dynamic_cast works. I have a class interfaceElement with a class menu derived from it. In my program, I create no objects of class interfaceElement. When executing the following code (executing the line with dynamic_cast, to be more precise), the bad_cast exception is thrown

void drawInterfaceElement(interfaceElement elem, int colour1, int colour2)
{
    if (elem.getType()=="MENU")
    {
        menu &cur = dynamic_cast<menu&>(elem);
        this->drawMenu(&cur,colour1,colour2);
    }
}

Why?

Vladgor
  • 21
  • 3

2 Answers2

2

Take interfaceElement by reference. Currently you incur slicing by taking by value, causing the menu subobject to be lost. dynamic_cast cannot cast to that type, causing std::bad_cast to be thrown (if you were converting to a pointer, a null pointer would be returned).

See What is object slicing?

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253
  • I have taken interfaceElement by reference, it didn't help. The same error is still thrown. – Vladgor May 08 '15 at 11:48
  • @Vladgor Your vector should hold `interfaceElement*` or `shared_ptr`. You have slicing going on there too. – David G May 08 '15 at 13:07
2

The problem is that you are passing elem by value. So it is an interfaceElement object and cannot be case to a derived type.

You need to pass by reference:

void drawInterfaceElement(interfaceElement& elem, int colour1, int colour2)
                                          ^
juanchopanza
  • 223,364
  • 34
  • 402
  • 480