Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- class BadShapeCreation {
- string type;
- public:
- BadShapeCreation(string type):type(type) {}
- string what() { return "Cannot create type " + type; }
- };
- class Shape {
- public:
- virtual void draw() = 0;
- virtual void erase() = 0;
- virtual ostream& ins(ostream& os)const = 0;
- virtual ~Shape() {}
- static Shape* factory(const char* type) throw (BadShapeCreation);
- };
- ostream& operator<<(ostream& os, const Shape& obj) { return obj.ins(os); }
- class Circle: public Shape {
- static int counter;
- int no;
- Circle() { no=++counter; }
- friend class Shape;
- public:
- void draw() { cout <<"Circle "<< no <<" :draw\n"; }
- void erase() { cout <<"Circle "<< no <<" :erase\n"; }
- ~Circle() { cout <<"Circle "<< no <<" ~Circle\n"; }
- ostream& ins(ostream& os) const { return os <<"Circle "<< no; }
- };
- int Circle::counter=0;
- class Triangle: public Shape {
- static int counter;
- int no;
- Triangle() { no=++counter; }
- friend class Shape;
- public:
- void draw() { cout <<"Triangle "<< no <<" :draw\n"; }
- void erase() { cout <<"Triangle "<< no <<" :erase\n"; }
- ~Triangle() { cout <<"Triangle "<< no <<" ~Triangle\n"; }
- ostream& ins(ostream& os) const { return os<<"Triangle "<<no; }
- };
- int Triangle::counter=0;
- class Square: public Shape {
- static int counter;
- int no;
- Square() { no=++counter; }
- friend Shape* getObjS();
- public:
- void draw() { cout <<"Square "<< no <<" :draw\n"; }
- void erase() { cout <<"Square "<< no <<" :erase\n"; }
- ~Square() { cout <<"Square "<< no <<" ~Square\n"; }
- ostream& ins(ostream& os) const { return os<<"Square "<<no; }
- };
- int Square::counter=0;
- Shape* getObjS() { return new Square; }
- Shape* Shape::factory( const char* type ) throw (BadShapeCreation) {
- switch(type[0]) {
- case 'C': return new Circle;
- case 'T': return new Triangle;
- case 'S': return getObjS();
- default: throw BadShapeCreation(type);
- }
- }
- char * askForType() {
- char* s[] = { "Circle", "Square", "Triangle", "None" };
- return s[rand()%4];
- }
- int main() {
- Shape ** shapes;
- cout <<"Enter the number of objects: ";
- int n;
- cin >> n;
- shapes = new Shape *[n];
- for(int i=0; i<n; i++) {
- Shape * s;
- try {
- s = Shape::factory(askForType());
- } catch(BadShapeCreation e) {
- cout << e.what() << endl;
- i--;
- continue;
- }
- shapes[i] = s;
- }
- cout<<"\n The Objects Are:\n";
- for(int i=0; i<n; i++) {
- cout << i <<" "<<*shapes[i]<<endl;
- }
- cout<<"\n Operating the objects:\n";
- for(int i=0; i<n; i++) {
- shapes[i]->draw();
- shapes[i]->erase();
- }
- cout<<"\n Purging the objects:\n";
- for(int i=0; i<n; i++) delete shapes[i];
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment