Calling the inheritance polymorphism function

class Shape 
{
   public:
      virtual void draw() const {cout<<"draw shape"<<endl;}
};



class Point : public Shape 
{
   public:
      Point( int a= 0, int b = 0 ) {x=a; y=b;}  // default constructor
      int getx() const {return x;}
      int gety() const {return y;}
      virtual void draw() const {cout<<"draw point("<<x<<","<<y<<")\n";}
   private:
      int x, y;   // x and y coordinates of Point
};


class Circle : public Point 
{
   public:  // default constructor
      Circle( double r = 0.0, int x = 0, int y = 0 ):Point(x,y) {radius=r;}
      virtual void draw() const 
      {cout<<"draw circle("<<getx()<<","<<gety()<<","<<radius<<")\n";}
   private:
      double radius;   // radius of Circle
};

void functionCall(Shape *arrayOfShapes[3])
{
    Shape shape;
    Point point( 7, 11 );            // create a Point
    Circle circle( 3.5, 22, 8 );     // create a Circle

    arrayOfShapes[0] = &shape;
    arrayOfShapes[1] = &point;
    arrayOfShapes[2] = &circle;

}

int main()
{


    Shape *arrayOfShapes[3];

    functionCall(arrayOfShapes);
    for(int i=0; i<3; ++i)
    arrayOfShapes[i]->draw();

    return 0;
}

      

When I tried to run, a segmentation error occurred. It looks like the main function can't get the object arrayOfShapes[3]

?

Is there a way to call a function that passes in an object pointer and returns an object pointer when done?

+3


source to share


1 answer


You cannot create shapes in a local function like this, because placing the addresses of local variables in an array makes them accessible outside of their scope:

Shape shape;
arrayOfShapes[0] = &shape; // <<== Pointer to local

      

However, you can do this:

arrayOfShapes[0] = new Shape;
arrayOfShapes[1] = new Point( 7, 11 );
arrayOfShapes[2] = new Circle( 3.5, 22, 8 );

      

This approach creates forms in heap, allowing them to be used when the function returns.



Note: Even if Circle

a source is required, the circle is definitely not a point. Hence, this expression is not logical:

class Circle : public Point // This implies that Circle is a Point

      

While you could argue that a point is a circle with a zero radius, structuring such inheritance would be a bad idea. The best approach is to Circle

contain Point

as its start:

class Circle : public Shape 
{
   public:
      const Point origin;
      // default constructor
      Circle( double r = 0.0, int x = 0, int y = 0 ):origin(x,y),
 radius(r) {}
      virtual void draw() const 
      {cout<<"draw circle("<<origin.getx()<<","<<origin.gety()<<","<<radius<<")\n";}
   private:
      double radius;   // radius of Circle
};

      

+7


source







All Articles