The task was to write function that compare areas of two random generated geometric shapes (circle, square, rectangle) using base class with virtual function.
Am I doing it right in terms of memory management?
Will my figures generated inside generateRandomShape() by new Square() etc. last in memory outside this function untill I manually delete them?
#include <iostream>
#include <cstdlib>
#include <ctime>
#define _USE_MATH_DEFINES
#include <cmath>
#include <vector>
#define M_PI 3.14159265358979323846
class Shape {
public:
virtual float area() = 0;
};
class Square : public Shape {
protected:
float sideA;
public:
Square(float sideA) : sideA(sideA) {}
float area() { return sideA * sideA; }
};
class Circle : public Shape {
protected:
float radius;
public:
Circle(float radius) : radius(radius) {}
float area() { return M_PI * radius * radius; }
};
class Rectangle : public Shape {
protected:
float sideA, sideB;
public:
Rectangle(float sideA, float sideB) : sideA(sideA), sideB(sideB) {}
float area() { return sideA * sideB; }
};
void compareAreasOffigures(Shape* a, Shape* b){
if (a->area() == b->area()) {
std::cout << "Areas of two shapes are equal." << std::endl;
}
else if (a->area() > b->area()) {
std::cout << "Area of first Shape is bigger." << std::endl;
}
else {
std::cout << "Area of second Shape is bigger." << std::endl;
}
}
Shape * generateRandomShape() {
int Shape;
Shape = rand() % 3;
switch (Shape) {
case 0: {
int sideA = rand() % 100;
std::cout << "Square was generated, side: " << sideA << std::endl;
return new Square(sideA);
break;
}
case 1: {
int sideA = rand() % 100;
int sideB = rand() % 100;
std::cout << "Rectangle was generated, side A: " << sideA << " side B: " << sideB << std::endl;
return new Rectangle(sideA, sideB);
break;
}
case 2: {
float radius = rand() % 100;
std::cout << "Circle was generated, radius: " << radius << std::endl;
return new Circle(radius);
break;
}
default: return NULL;
}
}
int main(void){
srand(time(0));
std::vector<Shape*> shapes;
shapes.push_back(generateRandomShape());
shapes.push_back(generateRandomShape());
compareAreasOffigures(shapes[0], shapes[1]);
for (auto v : shapes) { delete v; } //cleanup
shapes.clear();
return EXIT_SUCCESS;
}