Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C:ShapeV2.cpp // Alternative to ShapeV.cpp #include <iostream> #include <vector> #include "../purge.h" using namespace std; class Shape { Shape(Shape&); // No copy-construction protected: Shape() {} // Prevent stack objects // But allow access to derived constructors public: enum type { tCircle, tSquare, tTriangle }; virtual void draw() = 0; virtual ~Shape() { cout << "~Shape\n"; } static Shape* make(type); }; class Circle : public Shape { Circle(Circle&); // No copy-construction Circle operator=(Circle&); // No operator= protected: Circle() {}; public: void draw() { cout << "Circle::draw\n"; } ~Circle() { cout << "~Circle\n"; } friend Shape* Shape::make(type t); }; class Square : public Shape { Square(Square&); // No copy-construction Square operator=(Square&); // No operator= protected: Square() {}; public: void draw() { cout << "Square::draw\n"; } ~Square() { cout << "~Square\n"; } friend Shape* Shape::make(type t); }; class Triangle : public Shape { Triangle(Triangle&); // No copy-construction Triangle operator=(Triangle&); // Prevent protected: Triangle() {}; public: void draw() { cout << "Triangle::draw\n"; } ~Triangle() { cout << "~Triangle\n"; } friend Shape* Shape::make(type t); }; Shape* Shape::make(type t) { Shape* S; switch(t) { case tCircle: S = new Circle; break; case tSquare: S = new Square; break; case tTriangle: S = new Triangle; break; } S->draw(); // Virtual function call return S; } int main() { vector<Shape*> shapes; cout << "virtual constructor calls:" << endl; shapes.push_back(Shape::make(Shape::tCircle)); shapes.push_back(Shape::make(Shape::tSquare)); shapes.push_back(Shape::make(Shape::tTriangle)); cout << "virtual function calls:\n"; for(int i = 0; i < shapes.size(); i++) shapes[i]->draw(); //!Circle c; // Error: can't create on stack purge(shapes); } ///:~