What is Meant by Pure Virtual Function in C++? | Scaler Topics
Sat Apr 22 2023 15:12:17 GMT+0000 (Coordinated Universal Time)
Saved by
@gaurav752
#include <iostream>
using namespace std;
// here is Abstract class
class Shape
{
public:
virtual float cal_Area() = 0; // cal_Area is a pure virtual function
};
class Square : public Shape
{
float a;
public:
Square(float l)
{
a = l;
}
float cal_Area()
{
return a*a; // returns area of square
}
};
class Circle : public Shape
{
float r;
public:
Circle(float x)
{
r = x;
}
float cal_Area()
{
return 3.14*r*r ;
}
};
class Rectangle : public Shape
{
float l;
float b;
public:
Rectangle(float x, float y)
{
l=x;
b=y;
}
float cal_Area()
{
return l*b; // returns the product of length and breadth
}
};
int main() // main function
{
Shape *shape;
Square s(3.4);
Rectangle r(5,6);
Circle c(7.8);
shape =&s;
int a1 =shape->cal_Area();
shape = &r;
int a2 = shape->cal_Area();
shape = &c;
int a3 = shape->cal_Area();
std::cout << "The area of square is: " <<a1<< std::endl;
std::cout << "The area of rectangle is: " <<a2<< std::endl;
std::cout << "The area of circle is: " <<a3<< std::endl;
return 0;
}
content_copyCOPY
https://www.scaler.com/topics/pure-virtual-function-in-cpp/
Comments