// example of virtual method file: virtual.cc // a Drawing is an ordered list of Shapes // There are various Shapes - all subclasses of Shape // To render() a Drawing you draw() each Shape* in the list // Compiler can't tell at compile time which draw() method to use // The SRGP (Simplified rastor Graphics System) is used to draw. // This is a C library based on X11 which requires an X server // g++ virtual.cc -lsrgp -lX11 extern "C" { #include "/users/faculty/sedgwick/C/srgp.h" //Graphics library } class Shape {protected: int x, y; //all shapes have one Point public: //protected accessible by subclasses Shape(int x1, int y1):x(x1), y(y1) {} //ctor void virtual draw()=0; //pure virtual - all subclasses must implement }; class Rect: public Shape {protected: int x2, y2; public: Rect(int x1, int y1, int x2, int y2):Shape(x1,y1),x2(x2),y2(y2){}//ctor void draw() { SRGP_rectangleCoord (x,y, x2,y2); } }; class Oval: public Rect { public: Oval(int x1, int y1, int x2, int y2) : Rect(x1,y1, x2,y2) {} //ctor void draw(){ SRGP_ellipse( SRGP_defRectangle(x,y,x2,y2) ); } }; class Drawing { Shape *p; // could point to Oval or Rect Drawing * next; // remaining elements of the Drawing public: Drawing(Shape *q, Drawing *r){p = q; next = r;} //ctor void render() { p->draw(); // draw first element if ( next ) next->render(); // render rest if any } }; int main() { Oval o1(100,100,200,200), o2(300,300,400,400); Rect r (50,50, 450,450); SRGP_begin("Drawing Window",500,500,1,FALSE); // open drawing window Drawing d1(&r, 0), // d d2 d1 d2(&o2, &d1),// [o1|,-]-->[o2|,-]-->[r| ,0] linked list of shapes d(&o1, &d2); d.render(); // will draw o1 then o2 and finally r /* At end of program wait for user to hit RETURN key before closing window*/ SRGP_setInputMode (KEYBOARD, EVENT); /* start monitoring keybd events */ SRGP_waitEvent(-1); /* wait indefinitely for RETURN key */ } /* Graphics Window disappears here */