Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ polymorphism: Checking data type of sub class [duplicate]

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?

like image 686
Amit S Avatar asked Nov 05 '10 15:11

Amit S


2 Answers

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).

like image 139
vitaut Avatar answered Oct 03 '22 21:10

vitaut


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.

like image 44
Fred Larson Avatar answered Oct 03 '22 22:10

Fred Larson