Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 672
Chad Avatar asked Nov 21 '08 03:11

Chad


People also ask

How do you check if an object belongs to a certain class in C++?

C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.

How can you tell what type of object something is?

Use the typeof() Function to Check Whether a Value Is an Object or Not in JavaScript. We can check the type of objects using the typeof() function.

How do I check if an object is an instance of a given class or of a subclass of it?

The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).

What is subclass in C?

Sub Class: The class that inherits properties from another class is called Subclass or Derived Class.


2 Answers

 

class Base {   public: virtual ~Base() {} };  class D1: public Base {};  class D2: public Base {};  int main(int argc,char* argv[]); {   D1   d1;   D2   d2;    Base*  x = (argc > 2)?&d1:&d2;    if (dynamic_cast<D2*>(x) == nullptr)   {     std::cout << "NOT A D2" << std::endl;   }   if (dynamic_cast<D1*>(x) == nullptr)   {     std::cout << "NOT A D1" << std::endl;   } } 
like image 55
Martin York Avatar answered Sep 28 '22 05:09

Martin York


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".

like image 39
Dima Avatar answered Sep 28 '22 05:09

Dima