If your types are polymorphic (i.e. if they have at least one virtual
function), you can use dynamic_cast<>
. The result of dynamic_cast<>
will be a null pointer (i.e. nullptr
for C++11, NULL
for C++03) in case the pointed object is not actually an instance of the specified class, or of a derived class thereof:
Container cont;
Content1* pContent1 = dynamic_cast<Content1*>(cont.c);
if (pContent1 != nullptr)
{
// cont.c points to an instance of Content1
// or a class derived from Content1
}
A common practice is to make the destructor of your base class virtual, so that objects of a class derived from your base class can be delete
d through a base class pointer (if the destructor is not virtual
, attempting to do so results in undefined behavior):
class Content //Abstract.
{
public:
virtual ~Content() { }
// ^^^^^^^
};