In C , achieving the equivalent functionality of Java's instanceof operator involves a technique known as runtime type identification (RTTI) using dynamic_cast. This allows you to verify whether a given object, stored as a pointer or reference to its base class, points to a specific derived class instance.
To check if an object pointed to by a pointer or reference to the base class (old) is of a specific derived class type (NewType), you can use the following syntax:
if(NewType* v = dynamic_cast<NewType*>(old)) { // old was safely casted to NewType v->doSomething(); // Access specific methods of NewType }
It's important to note that dynamic_cast requires compiler support for RTTI, which must be enabled during compilation.
However, it's crucial to carefully consider the necessity of dynamic_cast before using it. In general, it indicates a potential design issue. One should strive for more robust and type-safe approaches, such as:
The above is the detailed content of How Can I Implement Java's `instanceof` Operator in C ?. For more information, please follow other related articles on the PHP Chinese website!