Home >Backend Development >C++ >How Can I Determine an Object's Type at Runtime in C ?
Finding the Type of an Object in C
An object's type can be determined using dynamic_cast. This method dynamically casts a datum from one pointer or reference type to another, verifying the cast's validity at runtime.
Usage:
To cast to a pointer type:
TYPE* dynamic_cast<TYPE*>(object);
To cast to a reference type:
TYPE& dynamic_cast<TYPE&>(object);
Result:
Runtime Type Information (RTTI)
Dynamic_cast relies on RTTI, which is only available for polymorphic classes (i.e., those with at least one virtual method). In practice, this is not a significant limitation, as most base classes have a virtual destructor for proper cleanup in derived classes.
Example:
Here is an example using dynamic_cast to check if an object is of type B:
class A {}; class B : public A { public: void b_function() {} }; void func(A& obj) { B* b_ptr = dynamic_cast<B*>(&obj); if (b_ptr != nullptr) { b_ptr->b_function(); // Object is of type B } else { std::cout << "Object is not of type B" << std::endl; } }
The above is the detailed content of How Can I Determine an Object's Type at Runtime in C ?. For more information, please follow other related articles on the PHP Chinese website!