215: Create a C++ program that uses single inheritance to model a simple shape hierarchy. Implement a base class "Shape" with a virtual function "printArea." Derive classes "Rectangle" and "Triangle" from "Shape" and override the "printArea" function to calculate and display their respective areas.

 

// Create a C++ program that uses single inheritance to model a simple shape hierarchy.
// Implement a base class "Shape" with a virtual function "printArea." Derive classes
// "Rectangle" and "Triangle" from "Shape" and override the "printArea" function to
// calculate and display their respective areas.

#include <iostream>
using namespace std;
class Shape
{
public:
    virtual void printArea() {cout << "Make object of specific shape\n";}
};

class Rectangle : protected Shape
{
private:
    float length, width;

public:
    Rectangle(float l = 0, float w = 0) { length = l, width = w; }
    void printArea() override { cout << "Area of Rectangle: " << length * width << endl; }
};

class Triangle : protected Shape
{
private:
    float base, height;

public:
    Triangle(float b = 0, float h = 0) { base = b, height = h; }
    void printArea() override { cout << "Area of Triangle: " << 0.5 * base * height << endl; }
};

class Square : protected Shape
{
private:
    float length;

public:
    Square(float l = 0) { length = l; }
    void printArea() override { cout << "Area of Square: " << length * length << endl; }
};
int main()
{
    Rectangle r1(12.5, 4.2);
    Triangle t1(10.2, 4.7);
    Square s1(4.56);
    r1.printArea();
    t1.printArea();
    s1.printArea();

    return 0;
}


Comments

Popular posts from this blog

42: ***(Syntax)*** Calculating number of characters and spaces in a string 1- Make a program to calculate the number of characters in a string 2- Modify this and also tell how many spaces are there in that sentence

96: ***(Syntax)*** Functions and Global Variables