I am not able to compile the following code snippet:
struct Base
{
int valor;
Base()
: valor(1)
{ }
};
struct Hija : Base
{
int func()
{ return valor; }
};
int main()
{
Base* punteroBase = new Hija;
Hija* punteroHija = dynamic_cast<Hija*>(punteroBase);
std::cout << punteroHija->func();
}
The error that appears to me is the following:
main.cpp:21:54: error: cannot dynamic_cast 'punteroBase' (of type 'struct Base*') to type 'struct Hija*' (source type is not polymorphic)
Looking at the code it is clear that both classes are related via inheritance and yet it dynamic_cast
does not work.
What is causing this problem? How can I solve that?
Your base class does not have any virtual methods, and therefore is not polymorphic, and only polymorphic classes generate one
vtable
(the table that stores, for each memory address at runtime, the derived type with which it was created the object, necessary for thedynamic_cast
).If you don't need any particular function to be virtual, you can make the destructor virtual:
If you don't need your object to be polymorphic (to save one
vtable
for a class that doesn't really need it), and you know the derived type, replace it with astatic_cast
and you're done:For this, never do a
reinterpret_cast
, becausestatic_cast
they take into account possible alignment differences and thereinterpret_cast
does not, although in efficiency they are the same.