[ create a new paste ] login | about

Link: http://codepad.org/YyjMJuIw    [ raw code | output | fork ]

C++, pasted on Nov 13:
/* Template version of figure hierarchy */
#include <iostream>
#include <cstdlib>
#include <typeinfo>
using namespace std;
 
template <class T> class figure {
protected:
    T x, y;
public:
    figure(T i, T j) {
        x = i;
        y = j;
    }
    virtual T area() = 0;
};
 
template <class T>  class triangle : public figure<T> {
public:
    triangle(T i, T j) : figure<T>(i, j) {}
    T area() {
        return 0.5*figure<T>::x*figure<T>::y;
    }
};
 
template <class T> class rectangle : public figure<T> {
public:
    rectangle(T i, T j) : figure<T>(i, j) {}
    T area() {
        return figure<T>::x * figure<T>::y;
    }
};
 
template <class T> class circle : public figure<T> {
public:
    circle(T i, T j=0) : figure<T>(i, j) {}
    T area() {
        return 3.14 * figure<T>::x * figure<T>::x;
    }
};
 
/* Fabric of objects of class figure */
figure<double> *generator() {
    switch(rand() % 3) {
        case 0: return new circle<double>(10.0);
        case 1: return new triangle<double>(10.1, 5.3);
        case 2: return new rectangle<double>(4.3, 5.7);
    }
    return 0;
}
 
int main() {
    figure<double> *p; /* pointer to the base class */
    int i;    
    int t = 0, r = 0, c = 0;
    
    /* generating and counting objects */
    for (i = 0; i < 10; i++) {
        p = generator(); /* generating object */
        cout << "Object has type " << typeid(*p).name();
        cout << ". ";
        
        /* keeping this object in mind */
        if(dynamic_cast< triangle <double> *>(p)) t++;
        if(dynamic_cast< rectangle<double> *>(p)) r++;
        if(dynamic_cast< circle   <double> *>(p)) c++;
    
        /* Output square of the figure */
        cout << "The square of the figure is" << p->area() << endl;
    }
    
    cout << endl;
    cout << "There was generated next objects:\n";
    cout << "  triangles: " << t << endl;
    cout << "  rectangles: " << t << endl;
    cout << "  circles: " << c << endl;
    
    return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Object has type 8triangleIdE. The square of the figure is26.765
Object has type 8triangleIdE. The square of the figure is26.765
Object has type 6circleIdE. The square of the figure is314
Object has type 8triangleIdE. The square of the figure is26.765
Object has type 9rectangleIdE. The square of the figure is24.51
Object has type 8triangleIdE. The square of the figure is26.765
Object has type 8triangleIdE. The square of the figure is26.765
Object has type 6circleIdE. The square of the figure is314
Object has type 6circleIdE. The square of the figure is314
Object has type 8triangleIdE. The square of the figure is26.765

There was generated next objects:
  triangles: 6
  rectangles: 6
  circles: 3


Create a new paste based on this one


Comments: