Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is C++11's equivalent of Java's instanceof

I want to know what the modern C++11 equivalent of Java's instanceof. I have seen this SO post but it is quite old and was wondering if there's a more modern, better solution in C++11?

I was hoping there's a possibility of using a switch construct without having to resort to a manual enum class.

class A {

};

class B : public A {

}

class C : public A {

}

on_event(A& obj)
{
    switch (obj) {
       case A:
       case B:
       case C:
    }
}

My base class does not have any virtual methods or functions. I am representing an expression tree for a parser and the base class is just a polymorphic holder - like an ADT in Haskell/OCaml.

like image 664
pezpezpez Avatar asked Oct 12 '14 12:10

pezpezpez


People also ask

What can I do instead of Instanceof?

The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.

Does C++ have Instanceof?

C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.

What is difference between getClass method and Instanceof operator?

Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.

What is an instance C++?

In object-oriented programming (OOP), an instance is a specific realization of any object. An object may be different in several ways, and each realized variation of that object is an instance. The creation of a realized instance is called instantiation.


1 Answers

The same answer still applies, and has always been like this in C++:

if (C * p = dynamic_cast<C *>(&obj))
{
    // The type of obj is or is derived from C
}
else
{
    // obj is not a C
}

This construction requires A to be polymorphic, i.e. to have virtual member functions.

Also note that this behaviour is different from comparing typeid(obj) == typeid(C), since the latter tests for exact type identity, whereas the dynamic cast, as well as Java's instanceof, only test for the target type to be a base class of the type of the most-derived object.

like image 122
Kerrek SB Avatar answered Oct 02 '22 16:10

Kerrek SB