Home >Backend Development >C++ >What's the Difference Between `static_cast` and `dynamic_cast` in C ?
Dynamic and Static Casting in C
The concepts of dynamic_cast and static_cast in C can be confusing, especially when dealing with polymorphic classes. To understand these concepts better, let's consider their C equivalents from a high-level perspective.
static_cast<>
The static_cast<> operation in C is a safe compile-time cast. It ensures that the destination and source types are related, preventing data corruption. If the types are not related, a compilation error will occur.
In the example below, the static_cast<> operation safely casts a pointer to a base class to a pointer to a derived class:
class B {}; class D : public B {}; D* d = new D; B* b = static_cast<B*>(d); // Safe compile-time cast
dynamic_cast<>
Unlike static_cast<>, dynamic_cast<> is a run-time cast. It checks at runtime if the actual type of the pointer matches the target type. It can handle casting both from base to derived (B2D) and derived to base (D2B) classes.
For D2B casts, dynamic_cast<> simply returns a NULL pointer if the cast is invalid. However, for B2D casts, the class hierarchy must support polymorphism, meaning at least one virtual function must be defined in the base class.
In the following example, dynamic_cast<> is used to safely cast a pointer to a base class to a pointer to a derived class:
class Base { virtual void DoIt() = 0; }; class Foo : public Base {}; class Bar : public Base {}; Base* base = new Foo; Foo* foo = dynamic_cast<Foo*>(base); // Safe run-time cast
If base actually pointed to a Bar object, the dynamic_cast<> operation would return NULL. This ensures type safety and prevents undefined behavior.
The above is the detailed content of What's the Difference Between `static_cast` and `dynamic_cast` in C ?. For more information, please follow other related articles on the PHP Chinese website!