Search code examples
c++oopinheritancemultiple-inheritancedynamic-cast

C++ - Is it possible to check derived class type in multiple inheritance?


In the code that is below I want to count the number of occurrences of objects of class B from the std::vector using dynamic_cast conversion. But the result is 2 and it should be 1. This happens because dynamic_cast checks object of class D as an object of class B because of the inheritance.

Is there any possible way to check the derived class type for multiple inheritance without having this problem? Is there any Java instanceof equivalent in C++ for this situation?

// Example program
#include <iostream>
#include <string>
#include <vector>


using namespace std;

class Base{

public:  
Base(){};
virtual ~Base(){};
};

class A:public virtual Base{
public:
A() {};
virtual ~A(){};

};

class B:public virtual Base{
public:
B(){};
virtual ~B(){};


};


class D: public A, public B{
public:

D(){};
virtual ~D(){};

};

int main()
{

 int c=0;
std::vector<Base*> v;
std::vector<Base*>::iterator myIt;

v.push_back(new Base());
v.push_back(new A());
v.push_back(new B());
v.push_back(new D());

for(myIt=v.begin(); myIt!=v.end();myIt++)
    if(B* object=dynamic_cast<B*>(*myIt))
        c++;
cout<<c<<endl;
return 0;
}

Solution

  • You are relying on RTTI already, so this will not incur much more cost. What you could do is replace the dynamic cast by a call to typeid. It will only check for exact dynamic type:

    // At the top
    #include <typeinfo>
    #include <typeindex>
    
    //...
    
    std::type_index const b_ti = typeid(B);
    
    for(myIt=v.begin(); myIt!=v.end();myIt++)
        if(b_ti == typeid(**myIt)) // Need to pass an lvalue of type B, hence the double asterisk
            c++;
    

    Side note, but you should consider replacing the loop by a range based for loop. It'll make the whole thing more readable:

    for(Base *item : v)
      if(b_ti == typeid(*item))
        ++c;
    

    Or better yet, a named algorithm:

    c = std::count_if(begin(v), end(v), 
          [&](Base *item) { return b_ti == typeid(*item); }
        );