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
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
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?
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With