I went to a job interview today and was given this interesting question.
Besides the memory leak and the fact there is no virtual dtor, why does this code crash?
#include <iostream>
//besides the obvious mem leak, why does this code crash?
class Shape
{
public:
virtual void draw() const = 0;
};
class Circle : public Shape
{
public:
virtual void draw() const { }
int radius;
};
class Rectangle : public Shape
{
public:
virtual void draw() const { }
int height;
int width;
};
int main()
{
Shape * shapes = new Rectangle[10];
for (int i = 0; i < 10; ++i)
shapes[i].draw();
}
You cannot index like that. You have allocated an array of
Rectanglesand stored a pointer to the first inshapes. When you doshapes[1]you’re dereferencing(shapes + 1). This will not give you a pointer to the nextRectangle, but a pointer to what would be the nextShapein a presumed array ofShape. Of course, this is undefined behaviour. In your case, you’re being lucky and getting a crash.Using a pointer to
Rectanglemakes the indexing work correctly.If you want to have different kinds of
Shapes in the array and use them polymorphically you need an array of pointers to Shape.