C++ equivalent of instanceof

C++Server Side ProgrammingProgramming

C++ has no direct method to check one object is 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 the given class is base of the given object or not. Here we will change the style of it like the java instanceof. Let us see the code.

Example Code

#include <iostream>
using namespace std;
template<typename Base, typename T>
inline bool instanceof(const T*) {
   return is_base_of<Base, T>::value;
}
class Parent{ };
class Child : Parent { };
class AnotherClass{};
int main() {
   Child *c;
   if(instanceof<Child>(c)) {
      cout << "c is instance of Child class" << endl;
   } else {
      cout << "c is not instance of Child class" << endl;
   }
   if(instanceof<Parent>(c)) {
      cout << "c is instance of Parent class" << endl;
   } else {
      cout << "c is not instance of Parent class" << endl;
   }
   if(instanceof<AnotherClass>(c)) {
      cout << "c is instance of AnotherClass class" << endl;
   } else {
      cout << "c is not instance of AnotherClass class" << endl;
   }
}

Output

c is instance of Child class
c is instance of Parent class
c is not instance of AnotherClass class
raja
Published on 28-May-2019 15:46:28
Advertisements