C++ Program to find area perimeter of a rectangle using virtual function


In this program, You will learn how to find the area perimeter of a rectangle using a virtual function in C++.


virtual void calculate() { 
    //statement
}

Example: How to find the area perimeter of a rectangle using a virtual function in C++.

#include<iostream>
using namespace std;

class First {
public:

   virtual void calculate() {
       cout << "Area Perimeter of a Rectangle";
   }
};

class Second : public First {
public:

   int width, height, area, perimeter;

   void calculate() {
       cout << "Enter Width of Rectangle:";
       cin>>width;

       cout << "Enter Height of Rectangle:";
       cin>>height;

       area = height*width;
       cout << "Area of Rectangle:" << area;

       perimeter = 2 * (height + width);
       cout << "\nPerimeter of Rectangle:" << perimeter;
   }
};

int main() {

   First *f;
   Second s;
   f = &s;
   f->calculate();

   return 0;
}

Output:

Enter Width of Rectangle:4
Enter Height of Rectangle:3
Area of Rectangle:12
Perimeter of Rectangle:14