# C++ - Calculate Area For Circle, Triangle and Rectangle

I have given a sample program to calculate the area for Circle, Triangle and Rectangle. This sample code is also an example for the concept of polymorphism.

## Source Code

#include <stdio.h>

#include <iostream>

#include <tchar.h>

#include <math.h>

class CShape

{

public:

virtual double CalculateArea() = 0;

};

class CTriangle : public CShape

{

double height;

double base;

double area;

public:

CTriangle() : base(12.2), height(18.8)

{

}

CTriangle(double b, double h) : base(b), height(h)

{

}

void SetHeight(double h) { height = h; }

void SetBase(double b) { base = b; }

double GetHeight() const { return height; }

double GetBase() const { return base; }

double CalculateArea()

{

area = base / 2 * height;

std::cout << "\nTriangle\nInput: Base = " << base << " Height = " << height << "\n";

std::cout << "Output: Area = ";

std::cout.width(8);

std::cout.precision(4);

std::cout.fill('*');

std::cout << area;

std::cout << "\n";

return area;

}

};

class CRectangle : public CShape

{

double length;

double width;

double area;

public:

CRectangle(double l, double w) : length(l), width(w)

{

}

CRectangle() : length(26.6), width(15.8)

{

}

void SetLength(double l) { length = l; }

void SetWidth(double w) { width = w; }

double GetLength() const { return length; }

double GetWidth() const { return width; }

double CalculateArea()

{

area = length * width;

std::cout << "\nRectangle\nInput: Length = " << length << " width = " << width << "\n";

std::cout << "Output: Area = ";

std::cout.width(8);

std::cout.precision(4);

std::cout.fill('*');

std::cout << area;

std::cout << "\n";

return area;

}

};

class CCircle : public CShape

{

double area;

public:

CCircle(double r = 6.8) : radius(r) { };

double CalculateArea()

{

std::cout << "Output: Area = ";

std::cout.width(8);

std::cout.precision(4);

std::cout.fill('*');

std::cout << area;

std::cout << "\n";

return area;

}

};

void main()

{

CRectangle *shapeRect = new CRectangle();

CCircle *shapeCircle = new CCircle();

CTriangle *shapeTriangle = new CTriangle();

CShape *shapeArea[] =  { shapeRect, shapeCircle, shapeTriangle };

for(int i = 0; i < sizeof(shapeArea) / sizeof(shapeArea[0]); i++)

shapeArea[i]->CalculateArea();

shapeRect->SetLength(16.8);

shapeRect->SetWidth(8.8);

shapeTriangle->SetBase(2.5);

shapeTriangle->SetHeight(3.8);

for(int i = 0; i < sizeof(shapeArea) / sizeof(shapeArea[0]); i++)

shapeArea[i]->CalculateArea();

delete shapeRect;

delete shapeCircle;

delete shapeTriangle;

}

## Output

Rectangle

Input: Length = 26.6 width = 15.8

Output: Area = ***420.3

Circle

Output: Area = ***145.3

Triangle

Input: Base = 12.2 Height = 18.8

Output: Area = ***114.7

Rectangle

Input: Length = 16.8 width = 8.8

Output: Area = ***147.8

Circle