Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninvasive polymorphism

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?

like image 842
Mikarnage Avatar asked Dec 21 '22 17:12

Mikarnage


1 Answers

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
}
like image 123
Andrey Avatar answered Dec 24 '22 01:12

Andrey