Write a program to create a class shape with functions to find volume of the shapes and display the name of the shape and other essential component of the class. Create derived classes sphere , cuboid and cone each having overridden functions area and display. Write a suitable program to illustrate virtual functions and virtual destructor
#include <iostream>
constexpr float kPi = 3.1415926f;
struct Shape {
virtual float GetVolume() const = 0;
virtual void Display() const = 0;
virtual ~Shape() {
std::cout << "~Shape\n";
};
};
struct Sphere : Shape {
Sphere(float radius) : r { radius } {}
float GetVolume() const override {
return kPi * r * r * r * 4.f / 3.f;
}
void Display() const override {
std::cout << "Sphere";
}
~Sphere() {
std::cout << "~Sphere\n";
};
private:
float r; // radius
};
struct Cuboid : Shape {
Cuboid(float len, float w, float h)
: length { len }, width { w }, height { h } {}
float GetVolume() const override {
return length * width * height;
}
void Display() const override {
std::cout << "Cuboid";
}
~Cuboid() {
std::cout << "~Cuboid\n";
}
private:
float length, width, height;
};
struct Cone : Shape {
Cone(float height, float radius)
: h { height }, r { radius } {}
float GetVolume() const override {
return kPi * r * r * h / 3.f;
}
void Display() const override {
std::cout << "Cone";
}
~Cone() {
std::cout << "~Cone\n";
}
private:
float h, r;
};
int main() {
Shape *arr[3] = {
new Sphere{ 1.f },
new Cuboid {1.f, 1.f, 1.f },
new Cone {1.f, 1.f }
};
for (int i = 0; i < 3; i++) {
arr[i]->Display();
std::cout << " " << arr[i]->GetVolume() << '\n';
}
for (int i = 0; i < 3; i++) {
delete arr[i];
}
return 0;
}
Comments
Leave a comment