C Equivalent to Java's Instanceof: dynamic_cast and Alternative Approaches
Java's instanceof operator allows you to check if an object is an instance of a specific class or its subclasses. In C , you can achieve similar functionality using dynamic_cast.
<code class="cpp">if (NewType* v = dynamic_cast<NewType*>(old)) { // Cast succeeded, old is a NewType object v->doSomething(); }</code>
This approach requires runtime type information (RTTI) to be enabled in your compiler. However, dynamic_cast can come at a performance cost.
Alternative Approaches:
<code class="cpp">switch (old->getType()) { case BOX: // old is a Box object break; case SPECIAL_BOX: // old is a SpecialBox object break; }</code>
This approach does not require RTTI but is not suitable for multi-level inheritance.
Note: Consider the necessity of dynamic type checking as it can indicate design issues. Alternatives like virtual functions or the enum approach may provide better design and performance in many cases.
The above is the detailed content of How to Achieve Java\'s `instanceof` Functionality in C : `dynamic_cast` and Alternatives?. For more information, please follow other related articles on the PHP Chinese website!