Check for derived type (C++)

前端 未结 6 639
暗喜
暗喜 2020-12-09 12:18

How do I check at runtime if an object is of type ClassA or of derived type ClassB? In one case I have to handle both instances separately

ClassA* SomeClass:         


        
6条回答
  •  温柔的废话
    2020-12-09 13:00

    Use a dynamic_cast as follows:

    ClassA* SomeClass::doSomething(ClassA* a)
    {
        if (dynamic_cast(a)) {
            ...
        } else if (dynamic_cast(a)) {
            ...
        }
     }
    

    dynamic_cast(ptr) will return 0 in case ptr is not a pointer of type T, and will return a pointer of type T otherwise.

    dynamic_cast can usually be avoided and is an indicator of bad design / code. If you can avoid it, try to do so, as it requires RTTI in your final executable.

提交回复
热议问题