I am having trouble with programming this code. I believe that there is no syntax error in my code, yet I am still not getting the desired output.
#include <iostream>
#include <vector>
class Shape {
public:
Shape(int size) : size(size) {
data = new int[size];
for (int i = 0; i < size; ++i) {
data[i] = i;
}
}
virtual ~Shape() {
delete[] data;
}
virtual void printInfo() const {
std::cout << "Shape with size " << size << std::endl;
}
protected:
int* data;
int size;
};
class Circle : public Shape {
public:
Circle(int size, int radius) : Shape(size), radius(radius) {}
~Circle() {
delete[] data;
}
void printInfo() const override {
std::cout << "Circle with size " << size << " and radius " << radius << std::endl;
}
private:
int radius;
};
void printShapeInfo(const Shape& shape) {
shape.printInfo();
}
int main() {
std::vector<Shape*> shapes;
shapes.push_back(new Circle(5, 3));
shapes.push_back(new Shape(7));
for (const Shape* shape : shapes) {
printShapeInfo(*shape);
delete shape;
}
return 0;
}
This is the output I am expecting:
Circle with size 5 and radius 3
Shape with size 7
And this is the output I am receiving:
Circle with size 5 and radius 3
free(): double free detected in tcache 2
Aborted
To fix your code, you can either remove the delete[] data statement from the Circle’s destructor, or define a copy constructor and a copy assignment operator for the Shape class. Here is an example of the latter option: