Dynamic Polimorphism (Abastract Class) in C++

#include #include #include #include class Shape{ public: virtual void draw(){cout<<"Hello";}//a pure virtual function }; // an abstract class class Circle : public Shape{ int x, y, r; public: Circle(int x, int y, int r){ this->x=x; this->y=y; this->r=r; } void draw(){ circle(x, y, r); } }; class Color:public Shape{ int c; public: Color(int c){ this->c = c; } void draw(){ setcolor(c); } }; void main(){ int gd=DETECT, gm; initgraph(&gd, &gm,"c:\\turboc3\\bgi"); Shape *sp; int ch = 0; do{ if(kbhit()) if(getch()==27) break; switch(ch){ case 0: sp=new Color(random(16)); break; case 1: sp=new Circle(random(600), random(480), random(300)); break; } sp->draw(); delete sp; ch = (ch + 1) % 2; } while(1); }

No comments: