0

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.

possum
  • 1,837
  • 3
  • 9
  • 18
IOviSpot
  • 358
  • 3
  • 19
  • Why are you dynamic casting to `CPremiumHero`? Why wouldn't you use `DerivedClass` instead? – possum Dec 05 '21 at 22:19
  • 7
    Everything in a `std::vector` is a `BaseClass`, even if it was initialized using a `DerivedClass`. This is known as object slicing. You might want something like a `std::vector>`. `dynamic_cast` also requires your class to have at least one virtual function--usually at the very least the destructor, since without `virtual ~BaseClass();` it's unsafe to destroy a derived class via a pointer to base. – Nathan Pierson Dec 05 '21 at 22:19
  • Also I really doubt most questions along this line are about the "reverse process". There's lots of questions about downcasting and slicing and very few about upcasting. – Nathan Pierson Dec 05 '21 at 22:20
  • @NathanPierson Thanks, Nathan. Some code would me much appreciated. – IOviSpot Dec 05 '21 at 22:21

1 Answers1

0

You got this error because you haven't defined any virtual function. Check out this answer to understand the concept.

dynamic_cast and static_cast in C++

Andreas
  • 31
  • 1
  • 3
  • `DerivedClass* d_el = dynamic_cast(el)` returns nullptr in this case when el should be a DerivedClass. – IOviSpot Dec 06 '21 at 22:36