乐闻世界logo
搜索文章和话题

Dynamic_cast and static_cast in C++

1个答案

1

Dynamic_cast

dynamic_cast is used for safe downcasting in polymorphic hierarchies. It primarily converts base class pointers or references to derived class pointers or references within an inheritance hierarchy while verifying the validity of the conversion. If the conversion is invalid, dynamic_cast returns a null pointer or throws an exception (when used with references). It supports run-time type identification (RTTI).

Usage scenarios: When the exact type of the object to be converted is uncertain, dynamic_cast is highly useful. For example, in a polymorphic class hierarchy, you may need to confirm that a base class pointer actually points to a specific derived class instance before safely invoking functions of that derived class.

Example:

cpp
class Base { public: virtual void print() { cout << "Base" << endl; } }; class Derived : public Base { public: void print() { cout << "Derived" << endl; } void derivedOnlyFunction() { cout << "Derived Function" << endl; } }; void process(Base* base) { Derived* derived = dynamic_cast<Derived*>(base); if (derived) { derived->derivedOnlyFunction(); } else { cout << "Conversion failed." << endl; } }

In this example, if base actually points to an object of the Derived class, dynamic_cast succeeds, and we can safely call derivedOnlyFunction. Otherwise, the conversion fails and returns a null pointer.

Static_cast

static_cast is used for non-polymorphic conversions and does not consider the safety of polymorphic types. It is primarily used for converting numeric data types, such as integers and floating-point numbers, or for converting derived class pointers to base class pointers within a class hierarchy.

Usage scenarios: When you are certain that the conversion is safe and no runtime type checking is needed, static_cast is appropriate. It is more efficient than dynamic_cast because it does not incur the overhead of runtime type checking.

Example:

cpp
float f = 3.14; int i = static_cast<int>(f); // Safely converting a floating-point number to an integer class Base {}; class Derived : public Base {}; Derived d; Base* b = static_cast<Base*>(&d); // Converting a derived class pointer to a base class pointer

In this example, we convert a floating-point number to an integer and a derived class pointer to a base class pointer, both of which are checked at compile time.

In summary, dynamic_cast is used for scenarios requiring type safety, especially in polymorphic contexts, while static_cast is suitable when you know the conversion is safe and no runtime checks are needed.

2024年6月29日 12:07 回复

你的答案