Possible Duplicate:
Finding the type of an object in C++
Hello,
I am sorry if it's a duplicate but I was not able to find answer to my question here.
Let's assume we have following class structure in c++:
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
Now I have got a pointer to CPolygon object. How do I check if it's actually a pointer to the object of class CRectangle?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With