Ich ging heute zu einem Vorstellungsgespräch und bekam diese interessante Frage.
Warum stürzt dieser Code ab, abgesehen von dem Speicherverlust und der Tatsache, dass es keinen virtuellen dtor gibt?
#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 **es auf eine Reihe von Rechtecken zeigt. Dann sollte der Zugriff Formen [i] -> draw () gewesen sein;
->war ein Fehler eines Redakteurs.