You can indeed cast it (assuming you intended Dog
to be derived publicly from Animal
); but you would have to cast a reference or pointer. Your cast to a value would try to create a new Dog
from the Animal
that was passed in; and there is no suitable conversion for that.
// safest, if you can't guarantee the type
Dog & d = dynamic_cast<Dog&>(a); // throws if wrong type
Dog * d = dynamic_cast<Dog*>(&a); // gives null if wrong type
// fastest, if you can guarantee the type
Dog & d = static_cast<Dog&>(a); // goes horribly wrong if wrong type
Don't use reinterpret_cast
; that allows all sorts of crazy conversions, so it's easy to do something wrong. Don't use the C-style cast (Dog&)a
either - that allows even more conversions than reinterpret_cast
, and has a syntax that's subtle and difficult to search for.
In general, you shouldn't need a cast at all - try to design the base class so that it exposes everything you want to do with it, with no need to know the actual object type.