Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C++ equivalent of 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
The nearest possible functionality similar to "instanceof" can be achieved using dynamic_cast
Example Code
#includeusing namespace std; template inline bool instanceof(const T *ptr) { return dynamic_cast (ptr) != nullptr; } class Parent { public: virtual ~Parent() {} virtual void foo () { std::cout (ptr1)) { cout (ptr2)) { cout (ptr2)) { cout (ptr1)) { cout (ptr2)) { cout Output
p is an instance of the class Parent c is an instance of the class Parent c is an instance of the class Child p is not an instance of the class Child c is not an instance of AnotherClass class
Advertisements
