Может ли указатель на базовую точку указывать на массив производных объектов?

Я пошел сегодня на собеседование и получил этот интересный вопрос.

Почему, помимо утечки памяти и отсутствия виртуального dtor, происходит сбой этого кода?

#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();
}
98
задан Luc Danton 31 October 2012 в 02:48
поделиться