#include #include class Shape { public: Shape(){ printf("Shape() constructor\n"); xPos = 5; yPos = 5; } virtual void draw() const = 0; double perimeter() const { return(0); } double getX() { return xPos; } double getY() { return yPos; } protected: double xPos; double yPos; }; class Triangle : public Shape { public: Triangle() { printf("Triangle() constructor\n"); xPos = 2; yPos = 2; } virtual void draw() const { printf("This is a triangle!\n"); } }; int main(int argc, char* argv[]) { /* Shape* s = new Shape; s->draw(); printf("The x-coordinate of s is %lg\n", s->getX()); Triangle* t = new Triangle; t->draw(); // equivalent to (*t).draw(); printf("The x-coordinate of t is %lg\n", t->getX()); */ // Say I'm writing a graphics library /* Shape* allTheShapes[1000]; allTheShapes[0] = new Triangle; allTheShapes[1] = new Square; for(i = 0; i < 1000; i++){ allTheShapes[i]->draw() } */ // C++ does not allow this; Triangle may require // more memory than Shape and not fit in the same slot //Shape x = Triangle(); // So instead we use pointers Shape* r = new Triangle; r->draw(); //delete s; //delete t; delete r; return(0); }