What is Downcasting?
Downcasting is the term used in C++ for casting a pointer or reference to a base class to a derived class. C++ provides a special explicit cast called dynamic_cast that performs this conversion. Downcasting is the opposite of the basic object-oriented rule, which states objects of a derived class, can always be assigned to variables of a base class.
Since base class variables can only sometimes be assigned to variables of a derived class downcasting doesn't always work. Upcasting can be easy because you are moving up the hierarchy and classes can easily converge to a general class. There are several possibilities of a derived class. One has to find a safe way to downcast.
void myFunction(Vehicle* v1)
{
Car *c1 = dynamic_cast<Car*>(v1);
if(c1)
{
// we can safely use c1
}
}
C++ FAQ Home