Love this site? Hate it? Leave us some comments.
*/

Other Views

corner
*/

CPLUSPLUS FAQ - What is Downcasting

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
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings