Search code examples
c++classsubclassidentification

How do I check if an object's type is a particular subclass in C++?


I was thinking along the lines of using typeid() but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)


Solution

  • You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.

    I am assuming you have a situation like this:

    class Base;
    class A : public Base {...};
    class B : public Base {...};
    
    void foo(Base *p)
    {
      if(/* p is A */) /* do X */
      else /* do Y */
    }
    

    If this is what you have, then try to do something like this:

    class Base
    {
      virtual void bar() = 0;
    };
    
    class A : public Base
    {
      void bar() {/* do X */}
    };
    
    class B : public Base
    {
      void bar() {/* do Y */}
    };
    
    void foo(Base *p)
    {
      p->bar();
    }
    

    Edit: Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates Liskov substitution principle. Uncle Bob calls this an "anathema to Object Oriented Design".