In C , the equivalent of Java's instanceof operator for determining an object's type is dynamic_cast. It provides runtime type information when compiled with runtime type identification (RTTI) support enabled.
To use dynamic_cast, follow this syntax:
if(NewType* v = dynamic_cast<NewType*>(old)) { // Type conversion successful }
However, it's important to consider potential drawbacks before using dynamic_cast. Runtime type checking, while useful in certain scenarios, can indicate poor design principles. Alternative approaches include:
While dynamic_cast is widely used, keep in mind its potential cost. A workaround that may suffice in many cases is to add an enum representing object types and perform static casts based on the enum value.
The above is the detailed content of What's the C Equivalent of Java's `instanceof` Operator?. For more information, please follow other related articles on the PHP Chinese website!