A simple C++ question : is it possible to call a function or another based on the runtime type of a pointer?
For example I have a class A, and class B is a child of A.
I want to write a function f such that
f(A* a)
{//do something
}
f(B* b)
{//do something else
}
//call f()
A* a = new A();
A* b = new B();
f(a);//do something
f(b);//do something, but I'd like it to "do something else"
Additional precision : A and B are defined and instanced out of my code, so I can't use regular polymorphism with virtual functions on A and B...
I know you can use some RTTI, but is there a more elegant solution?
You may achieve that using dynamic_cast
:
f(A* a)
{
B* b = dynamic_cast<B*>(a);
if (b == nullptr)
//do something
else
//do something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With