Answer to Question #265720 in C++ for Amit

Question #265720

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

1
Expert's answer
2021-11-13T23:51:34-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS