Reputation: 38949
Say that I that I have these classes:
struct Parent {};
struct Child : public Parent {
void func() {}
};
Now say that I wanted to create a function like this:
void foo(Parent* arg) {
auto child = dynamic_cast<Child*>(arg);
if(child != nullptr) child->func();
}
But obviously that will obviously give me the error:
dynamic_cast
:Parent
is not a polymorphic type
So I can't do the dynamic_cast
step, is there a way that I can validate that arg
is in fact a Child*
at run-time?
Upvotes: 2
Views: 869
Reputation: 1034
No, you can't. The information you can get about an object at runtime is achieved using the RTTI
(Run Time Type Information
). The RTTI
of an object is stored within the virtual table of it's class.
Each object of a polymorphic class (i.e. a class which has one or more virtual functions, or a class which is derived from a polymorphic class) contains a vptr
, which is a pointer to the virtual table of the corresponding class. An object of a non-polymorphic type has no vptr
and there is not a virtual table for its class. Therefore you cannot use dynamic_cast
on non-polymorphic types.
So, as @lorro said, you should add a virtual function to Parent
, and the simplest option is adding a virtual destructor (which you should do anyway):
struct Parent {
virtual ~Parent() {}
};
Upvotes: 6
Reputation: 10880
Give your Parent
class a virtual function. Destructor comes into mind, for several reasons (like deleting child via base ptr, etc.).
Upvotes: 9