Consider the code:
class BaseClass { /* ... */ };
class DerivedClass : public BaseClass { /* ... */ };
std::vector<BaseClass> vClasses;
int main() {
BaseClass foo1;
vClasses.push_back(foo1);
BaseClass foo2;
vClasses.push_back(foo2);
DerivedClass bar;
vClasses.push_back(bar);
for (BaseClass& el : vClasses)
{
if (DerivedClass* d_el = dynamic_cast<CPremiumHero*>(&el)) {
d_el.CallMethodsFoundInDerivedClass();
}
else {
el.CallDefaultMethods();
}
}
}
How do I check that one of the elements from the vector is a DerivedClass, then using it further on? The if (DerivedClass* d_el = dynamic_cast<CPremiumHero*>(&el))
statement throws an error the operand of a runtime dynamic_cast must have a polymorphic class type
. I don't know what that means, neither do I know what other methods I should use.