0

Can anyone explain why the last line works? It seems like it is trying to cast a CRectangle as a CTriangle (which I imagine should fail?) but it outputs "5" as the function should.

// virtual members
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area () = 0;
      //{ return (0); }
  };

class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
      int triFunc(){return 5;}
  };

int main () 
{
  CPolygon* ppoly1 = new CRectangle;
  CPolygon* ppoly2 = new CTriangle;
  
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);

  cout << ppoly1->area() << endl;
  cout << ppoly2->area() << endl;

std::cout << dynamic_cast<CTriangle*>(ppoly2)->triFunc() << std::endl; //works (and should work)
  std::cout << dynamic_cast<CTriangle*>(ppoly1)->triFunc() << std::endl; //works (but seems like it shouldn't)

  return 0;
}

Thanks,

David

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by mitrmkar
0

dynamic_cast<CTriangle*>(ppoly1) gives you a NULL pointer, through which the call gets made. If you were to modify the (non-existent) object's state inside the triFunc() , then you would get a run-time error, but because you just return the constant value (5), it appears to 'work'.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.