C++ polymorphism: Checking data type of sub class
Ideally, you don't. You use polymorphism to just do the right thing:
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area() const = 0;
};
class CRectangle: public CPolygon {
public:
int area () const
{ return (width * height); }
};
Call area()
on your CPolygon pointer, and you'll get the area for a CRectangle if that's what it is. Everything derived from CPolygon will have to implement area()
or you won't be able to instantiate it.
You can do this by checking if dynamic_cast<CRectangle*>(ptr)
return non-null, where ptr
is a pointer to CPolygon
. However this requires the base class (CPolygon
) to have at least one virtual member function which you probably need anyway (at least a virtual destructor).
You can dynamic_cast it:
CRect* pRect = dynamic_cast<CRect*>(MyPolygonPointer);
if(pRect != 0)
{
//...it is a CRect
}
But naturally downcasting is a bad practice and should be used with caution. In a good design you don't care about the actual dynamic type of the pointer.