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();
}
Shape **
It's pointing to an array of Rectangles. Then the access should have been shapes[i]->draw(); – RedX->
was a mistake made by an editor. – R. Martinho Fernandes