Home >Backend Development >C++ >How Can I Determine an Object's Type at Runtime in C ?

How Can I Determine an Object's Type at Runtime in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 19:50:16354browse

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:

  • If the cast is successful and the object is of the desired type, the result is the pointer or reference to the object.
  • If the cast is unsuccessful (object is not of the desired type), the result is NULL for a pointer cast and throws a bad_cast exception for a reference cast.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn