Skip to main content

ProwessApps

Learn · Practice · Excel

  Define the class hierarachy as given . Find the area of a circle, rectangle, triangle using virtual function. Creation of Base class object should not be allowed.

C++ Code Example — Inheritance Programs

ADVERTISEMENT

  Define the class hierarachy as given . Find the area of a circle, rectangle, triangle using virtual function. Creation of Base class object should not be allowed.

Objective

Write a C++ program to demonstrate Pure Virtual Functions and Abstract Classes.

Algorithm / Approach

  1. Create a class Shape with a pure virtual function: virtual void area() = 0;.
  2. Create derived classes (Rectangle, Triangle, Circle) that inherit from Shape.
  3. Force every derived class to write its own unique implementation of void area().
  4. In main(), create objects of the derived classes and call their area functions.
main.cpp
#include<iostream>
using namespace std;
class Shape {
 public:
 virtual void area() = 0;
};
class Rectangle : public Shape {
 public:
 int l,b,ar;
 void area() {
  cout<<"Enter Length, Breadth ";
  cin>>l>>b;
  ar = l*b;
  cout<<"Area of Rectangle = "<< ar; 
  cout<< endl;
 }
};
class Triangle : public Shape {
 public:
 int h,b,ar;
 void area() {
  cout<<"Enter Height, Base ";
  cin>>h>>b;
  ar = h*b/2;
  cout<<"Area of Triangle = "<< ar;
  cout<< endl;
 }
};
class Circle : public Shape {
 public:
 int r,ar;
 void area() {
  cout<<"Enter Radius ";
  cin>>r;
  ar = 3.14*r*r;
  cout<<"Area of Circle = "<< ar;
  cout<< endl;
 }
};
int main() {
 Rectangle r;
 r.area();
 Triangle t;
 t.area();
 Circle c;
 c.area();
 return 0;
}

Expected Output

Enter Length, Breadth 4 3
Area of Rectangle = 12
Enter Height, Base 6 8
Area of Triangle = 24
Enter Radius 7
Area of Circle = 153

Explanation of the Program

  • A Pure Virtual Function (denoted by = 0) is a strict contract. It has no code body in the parent class. It simply forces every child class to create its own version of that function.
  • Any class that contains at least one Pure Virtual Function becomes an "Abstract Class". You are strictly forbidden from creating an object of an Abstract Class (e.g., Shape s; will cause a compilation error).

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT