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;
}