Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if the object is base class type

I have the following inheritance hierarchy

class A{
  virtual bool fun() = 0;
};

class B: public A{
...
}

class C: public B{
...
}

class D: public C{
...
}

class E: public B{
...
}

in the main program I am executing like

for(auto pA: ObjVector)
{
   if(pA->fun()){
       ...
   }
}

Now I would like to know pA is contains the base class B object. As far as I know 2 ways

  1. dynamic_cast the object and test for all derived classes if it fails for all dynamic_casts and only pass for B we are sure that the object is of type B

  2. Add one more interface method that will return the type enumeration value and identify the B object.

Is there is any other method to identifying the B class?

like image 508
Gilson PJ Avatar asked Dec 19 '16 05:12

Gilson PJ


People also ask

How do you check if an object is a certain type 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.

What is the base class of an object in C#?

A base class is the immediate “parent” of a derived class. A derived class can be the base to further derived classes, creating an inheritance “tree” or hierarchy. A root class is the topmost class in an inheritance hierarchy. In C#, the root class is Object .

How can you determine at run time the type of an object?

The typeid keyword is used to determine the class of an object at run time. It returns a reference to std::type_info object, which exists until the end of the program.


1 Answers

You can use the typeid operator. For example

if (typeid(*pA) == typeid(B)) {
    /* ... ptr points to a B ... */
}

this work ONLY when pA is exactly B

typeid - documentation

like image 117
Adrian Bobrowski Avatar answered Sep 23 '22 09:09

Adrian Bobrowski