Program to find area of different shapes using virtual function

In this we are going see a program to find area of different shapes using virtual function in C++ Programming Language.



The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include <conio.h>

class Shape
{
    public:
    int length, width;
    virtual int DimensionsArea(int l, int w)
    {
        length = l;
        width = w;
        return 0;
    }
};

class Rectangle : public Shape
{
    public:
    int DimensionsArea(int l, int w)
    {
        return l * w;
    }
};

class Triangle : public Shape
{
    public:
    int DimensionsArea(int b, int h)
    {
        return b * h / 2;
    }
};

void main()
{
    clrscr();
    int n1, n2;
    cout << "Enter the Height and Width: ";
    cin >> n1 >> n2;
    Rectangle objR;
    Triangle objT;
    Shape *obj1 = &objR;
    Shape *obj2 = &objT;
    cout << "Area of the Rectangle = " << obj1->DimensionsArea(n1, n2) << " sq units" << endl;
    cout << "Area of the Triangle = " << obj2->DimensionsArea(n1, n2) << " sq units";
    getch();
}

//.......Coded by SHREYA IDATE

The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
using namespace std;

class Shape
{
    public:
    int length, width;
    virtual int DimensionsArea(int l, int w)
    {
        length = l;
        width = w;
        return 0;
    }
};

class Rectangle : public Shape
{
    public:
    int DimensionsArea(int l, int w)
    {
        return l * w;
    }
};

class Triangle : public Shape
{
    public:
    int DimensionsArea(int b, int h)
    {
        return b * h / 2;
    }
};

int main()
{
    int n1, n2;
    cout << "Enter the Height and Width: ";
    cin >> n1 >> n2;
    Rectangle objR;
    Triangle objT;
    Shape *obj1 = &objR;
    Shape *obj2 = &objT;
    cout << "Area of the Rectangle = " << obj1->DimensionsArea(n1, n2) << " sq units" << endl;
    cout << "Area of the Triangle = " << obj2->DimensionsArea(n1, n2) << " sq units";
    return 0;
}

//.......Coded by SHREYA IDATE

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post