I’m trying to make some conditional actions depend on the type of polymorphic objects resolved at runtime.
Here is some pseudocode to illustrate what I mean:
class Base {
//base class impl
} ;
class Foo : public Base {
// foo class impl
};
class Bar : public Base {
// bar class impl
};
int main()
{
std::vector<Base*> v;
Base* A = new Foo();
Base* B = new Bar();
v.push_back(A);
v.push_back(B);
std::stack<Base*> s;
for (auto& ptr : v)
{
// push on stack if of type Foo, do nothing if of type Bar
}
}
Here is an implementation of this idea in Java.:
// for (...)
{
if (component instanceOf Foo)
{
stack.push(component)
}
}
What would be the correct way to implement this idea in C++?
>Solution :
This can be done with dynamic_cast:
if (auto* fooptr = dynamic_cast<Foo*>(ptr); fooptr != nullptr)
{
stack.push(fooptr);
}
This of course requires that the classes really are polymorphic, and have at least one virtual function (which should be the destructor).