0

Is it possible to cast an element of a vector of a base class to a derived class? If I use dynamic_cast, it returns null, even though the element was added as the derived class. If I add it like this, does all of the derived class information get lost? A static_cast works, but the member values are broken, which is why I guess the information gets lost when putting it into the vector of the base class. If it's not possible to do it with vectors, is there another way to have a collection of base class items that each have different derived classes and do something else depending on their derived class?

#include <vector>

class Base {
public:
    int x = 2;
    int y = 4;

    virtual void doSomething() {};
};

class Derived : public Base {
public:
    int x = 8;
    int y = 16;
    int z = 32;

    void doSomethingElse() {
        if (z == 32) {
            printf("Success!");
        }
    }
};

int main() {
    std::vector<Base> baseVector;

    Base base;
    Derived derived;

    baseVector.push_back(base);
    baseVector.push_back(derived);

    for (int i = 0; i < baseVector.size(); i++) {
        Base *ithBase = &baseVector[i];
        Derived *ithDerived = dynamic_cast<Derived *>(ithBase);
        if (ithDerived != nullptr) {
            ithDerived->doSomethingElse();
        }
    }

    return 0;
}
Lyxodius
  • 344
  • 1
  • 5
  • 12
  • No, you can't cast to the derived object, because the objects stored in the vector are only the base class objects. – 1201ProgramAlarm Dec 20 '21 at 18:33
  • `std::vector baseVector;` defines a `vector` of `Base`s. In order for a base class to refer to a derived class, it must be a reference or a pointer. Otherwise when you assign the derived instance to a base instance, the derived-ness gets sliced away and all you get is a plain old base. [You can't make a `vector` of references](https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references), so you need to use `std::vector baseVector;`, and with `Base*` one must always be wary of Cylons. – user4581301 Dec 20 '21 at 18:36

0 Answers0