Upcasting and Downcasting
I actually don’t really understand what this is about. Okay i do now.
Upcasting = Derived Class Base Class Downcasting = Base Class Derived Class
Upcasting
Upcasting is the process of converting a pointer or reference of a derived class to its base class.
Since the derived class is a specialized version of the base class, it contains all the properties and methods of the base class. Upcasting is therefore always safe and doesn’t require any special syntax or casting operators.
For example:
class Base {};
class Derived : public Base {};
Derived derived;
Base* basePtr = &derived; // Upcasting
Downcasting
Downcasting involves converting a pointer or reference of a base class to one of its derived classes.
Since the base class does not necessarily contain all the properties and methods of the derived class, downcasting can be risky and may lead to runtime errors if not done correctly.
In C++, downcasting typically requires explicit Type Casting using either dynamic_cast
(for polymorphic classes) or static_cast
(when the programmer is certain about the types).
So should I use
static_cast
ordynamic_cast
??
static_cast
: No runtime checking → Undefined Behavior on invalid casts.dynamic_cast
: Runtime type checking → Returns nullptr for pointers or throwsstd::bad_cast
for references on invalid casts.