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

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_