Slip 5 - B) Create a C++ base class Shape. Derive three different classes Circle, Sphere and Cylinder from shape class. Write a C++ program to calculate area of Circle, Sphere and Cylinder. (Use pure virtual function).

 Solution:

#include<iostream>
using namespace std;

class shape {
    public:
    virtual void area() = 0;
};

class circle: public shape {
   float r;

   public:
        void area() {
            cout << "\nEnter radius : ";
            cin >> r;
            cout << "\nArea of circle : " << (2.146*r*r);
        }
};


class rectangle: public shape {
int l,b;

    public:
    void area() {
        cout << "\nEnter length : ";
        cin >> l;
        cout << "\nEnter breadth : ";
        cin >> b;
        cout << "\nArea of rectangle : " << (l*b);
    }
};


class triangle: public shape {
int h,b;
    float a;

    public:
       void area() {
            cout << "\nEnter height : ";
            cin >> h;
            cout << "\nEnter breadth : ";
            cin >> b;
            cout << "\nArea of triangle : " << (0.5*h*b);
       }
};


int main() {
    circle c;
    c.area();

    cout << endl;

    rectangle r;
    r.area();

    cout << endl;

    triangle t;
    t.area();

    cout << endl;

   return(0);
}

Post a Comment

1 Comments

  1. this code is wrong ! the right one is here #include
    using namespace std;

    class Shape{
    public:
    virtual void area() = 0;
    };

    class Circale:public Shape{
    public:
    void area(){
    float r;
    cout << "Enter radious: ";
    cin >> r;
    cout << "The area of circale is: " << 3.14 * r * r << endl;
    }
    };

    class Sphear:public Shape{
    public:
    void area(){
    float r;
    cout << "\nEnter radious: ";
    cin >> r;
    cout << "\nThe Area of Sphear is: " << (4.0*3.14*r*r);
    }
    };

    class Cylender:public Shape{
    public:
    void area(){
    float r,h;
    cout << "Enter the radious: ";
    cin >> r;
    cout << "Enter the Height: ";
    cin >> h;

    cout << "The area of Sphear is: " <<2.0*3.14*r*(r+h);
    }
    };

    int main(){
    Shape *ptr;

    Circale obj;
    ptr = &obj;
    ptr->area();

    Sphear obj2;
    ptr = &obj2;
    ptr->area();

    Cylender obj3;
    ptr = &obj3;
    ptr->area();

    return 0;
    }

    ReplyDelete