C++ examples for Class:Polymorphism
A polymorphic class that encapsulates two-dimensional shapes
#include <iostream> #include <cstdlib> using namespace std; class Shape {// ww w. j a v a 2 s .c om protected: double x, y; public: Shape(double i, double j) { x = i; y = j; } double getx() { return x; } double gety() { return y; } virtual double area() = 0; }; // Create a subclass of Shape for triangles. class triangle : public Shape { public: triangle(double i, double j) : Shape(i, j) { } double area() { return x * 0.5 * y; } }; // Create a subclass of Shape for rectangles. class rectangle : public Shape { public: rectangle(double i, double j) : Shape(i, j) { } double area() { return x * y; } }; // Create a subclass of Shape for circles. class circle : public Shape { public: circle(double i, double j=0) : Shape(i, j) { } double area() { return 3.14 * x * x; } } ; // A factory for objects derived from Shape. Shape *factory() { static double i = (rand() % 100) / 3.0, j = (rand() % 100) / 3.0; i += rand() % 10; j += rand() % 12; cout << "Generating object.\n"; switch(rand() % 3 ) { case 0: return new circle(i); case 1: return new triangle(i, j); case 2: return new rectangle(i, j); } return 0; } bool sameshape(Shape *alpha, Shape *beta) { cout << "Comparing a " << typeid(*alpha).name() << " object to a " << typeid(*beta).name() << " object\n"; if(typeid(*alpha) != typeid(*beta)) return false; if(alpha->getx() != beta->getx() && alpha->gety() != beta->gety()) return false; return true; } int main() { // Create a base class pointer to Shape. Shape *p; // Generate Shape objects. for(int i=0; i < 6; i++) { // Generate an object. p = factory(); // Display the name of the object. cout << "Object is " << typeid(*p).name() << endl; // Display its area. cout << " Area is " << p->area() << endl; // Keep a count of the object types that have been generated. if(typeid(*p) == typeid(triangle)) cout << " Base is " << p->getx() << " Height is " << p->gety() << endl; else if(typeid(*p) == typeid(rectangle)) cout << " Length is " << p->getx() << " Height is " << p->gety() << endl; else if(typeid(*p) == typeid(circle)) cout << " Diameter is " << p->getx() << endl; cout << endl; } cout << endl; // Make some objects to compare. triangle t(2, 3); triangle t2(2, 3); triangle t3(3, 2); rectangle r(2, 3); // Compare two two_d_objects. if(sameshape(&t, &t2)) cout << "t and t2 are the same.\n"; if(!sameshape(&t, &t3)) cout << "t and t3 differ.\n"; if(!sameshape(&t, &r)) cout << "t and r differ.\n"; cout << endl; return 0; }