How to Achieve C Equivalent of Java's instanceof
In Java, the "instanceof" operator allows you to determine if an object belongs to a specific class or interface. In C , there are several methods to achieve this functionality.
Dynamic Casting with RTTI
One approach is using dynamic casting with Runtime Type Information (RTTI) enabled. This requires you to include the necessary headers:
#include
#include
And then you can perform a dynamic cast using:
if(NewType* v = dynamic_cast(old)) {
// old was safely casted to NewType
v->doSomething();
}
Note that this approach requires RTTI support to be enabled in your compiler.
Virtual Functions
Another method is to use virtual functions. You can define a virtual function in the base class and override it in derived classes. Then, you can check the dynamic type of an object by calling its virtual function:
class Base {
public:
virtual void doSomething() {}
};
class Derived : public Base {
public:
void doSomething() override {}
};
...
if(auto* derived = dynamic_cast(old)) {
derived->doSomething();
}
Type Switch
Finally, you can use a type switch to determine the dynamic type of an object. This approach relies on the type_info class:
if(old.IsSameAs(typeid(NewType))) {
// old was safely casted to NewType
NewType* v = static_cast(old);
v->doSomething();
}
Considerations
While these methods offer functionality similar to Java's "instanceof" operator, it's crucial to remember that dynamic casting and type checking can incur performance penalties. It's recommended to consider using alternative approaches such as virtual functions or type switches for better performance in critical applications.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3