In C++, we can check the type of an object at runtime using the typeid operator or the dynamic_cast operator.
#include <iostream>
#include <typeinfo> // for typeid
using namespace std;
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
};
int main() {
Base* basePtr = new Derived();
if (typeid(*basePtr) == typeid(Derived)) {
cout << "basePtr is an instance of Derived class" <<endl;
} else {
cout << "basePtr is not ..." <<endl;
}
delete basePtr;
return 0;
}
or dynamic_cast
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
};
int main() {
Base* basePtr = new Derived();
if (Derived* d_ptr = dynamic_cast<Derived*>(basePtr)) {
cout << "basePtr is an instance of Derived class" <<endl;
} else {
cout << "basePtr is not ..." <<endl;
}
delete basePtr;
return 0;
}
Top comments (6)
You neglected to mention that this works only if the object is a class that has at least one
virtual
member function.actually, i did not know about that, because every time i define Base class, i used at least virtual destructor in order to enable destructor of Derived class
Not every base class needs
virtual
functions or destructors. If their typical use is to be used directly (not via a pointer to reference to the base class), then addingvirtual
(1) bloats the object by addingsizeof(void*)
to it and (2) requires a virtual function call for the destructor (at least) that, if there are lots of such objects or they're created/destroyed in tight loops, is a real performance hit.could you explain more ? if we use Base class directly, do we need to define Derived class ?
Your question makes no sense. If you don't need any particular class (derived or not), then don't define it.
An example of what I'm talking about is if you did something like:
and you add a custom member function. In your code, you only ever use
my_string
,my_string*
, andmy_string&
. In particular, you never do:then the fact that the destructor of
std::string
is notvirtual
doesn't matter because you never usemy_string
polymorphically.I got it, sorry because I just focus on polymorphism