BCA
Object Oriented Programming using C++ Practical
Madras University
Program 4
Design and implement a class to represent a Solid object.
a. Apart from data members to represent dimensions, use a data member to
specify the type of solid.
b. Use functions to calculate volume and surface area for different solids.
SOURCE CODE:
#include <iostream>
#include <string>
using namespace std;
class Solid {
protected:
string type;
public:
Solid(const string& type) : type(type) {}
virtual ~Solid() {}
string getType() const {
return type;
}
virtual double volume() const = 0;
virtual double surfaceArea() const = 0;
};
class Cube : public Solid {
private:
double side;
public:
Cube(double side) : Solid("Cube"), side(side) {}
double volume() const override {
return side * side * side;
}
double surfaceArea() const override {
return 6 * side * side;
}
};
class Sphere : public Solid {
private:
double radius;
public:
Sphere(double radius) : Solid("Sphere"), radius(radius) {}
double volume() const override {
return (4.0 / 3.0) * 3.14159265358979323846 * radius * radius * radius;
}
double surfaceArea() const override {
return 4 * 3.14159265358979323846 * radius * radius;
}
};
class Cylinder : public Solid {
private:
double radius;
double height;
public:
Cylinder(double radius, double height) : Solid("Cylinder"), radius(radius), height(height) {}
double volume() const override {
return 3.14159265358979323846 * radius * radius * height;
}
double surfaceArea() const override {
return 2 * 3.14159265358979323846 * radius * (radius + height);
}
};
int main() {
Cube cube(3);
Sphere sphere(2);
Cylinder cylinder(2, 5);
Solid* solids[] = { &cube, &sphere, &cylinder };
for (Solid* solid : solids) {
cout << "Type: " << solid->getType() << endl;
cout << "Volume: " << solid->volume() << endl;
cout << "Surface Area: " << solid->surfaceArea() << endl;
cout << std::endl;
}
return 0;
}
No comments:
Post a Comment