0

I'm just a beginner on C++ and the object oriented stuffs. In transition from C. Please bear with my ignorance. This is in continuation with:

Can a pointer to base point to an array of derived objects?

#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();
}

The Class Shape contains a pure virtual function and hence it becomes an abstract class. Hence, on the first place, there should be a compiler error on creating an instance for it. But I don't get any compiler error.

Community
  • 1
  • 1
Vinoth
  • 301
  • 5
  • 12
  • can you post the code? we can't start answering without seeing what you've fed the compiler. – NirMH Jun 08 '14 at 12:34
  • sorry, I did not paste because it was on the source link which I had mentioned.. – Vinoth Jun 08 '14 at 12:37
  • You never create an instance of Shape. Where do you think you do? – luk32 Jun 08 '14 at 12:37
  • btw: the code you've posted contains a bug... change the `Shape` into a `Rectangle`... check the accepted answer – NirMH Jun 08 '14 at 12:37
  • Ok so, `Shape * shapes` just creates references and does not instantiate the Class Shape, hence there is no issue. Am I correct? – Vinoth Jun 08 '14 at 12:42
  • `Shape* Shapes` is a bug... but to your question, check the R-value... it is `= new Rectangle[10];` so you are created 10 objects of `Rectangle` not `Shape`. if the R-value was `= new Shape[10];` you'll get a compiler error of `trying to instantiate a pure virtual class` – NirMH Jun 08 '14 at 12:43

1 Answers1

2

Indeed Shape contains a pure virtual method, but it is not instantiated.

the main function contains an instantiation of Rectangle which is not a pure virtual class. so there is no problem

int main()
{
    Rectangle * shapes = new Rectangle[10];
    for (int i = 0; i < 10; ++i)
        shapes[i].draw();
}

-- I've re-post R. Martinho Fernandes code from that post accepted answer

NirMH
  • 4,769
  • 3
  • 44
  • 69