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