Alex Rivera | Logout

Inheritance - why is this illegal?

Asked 2012-08-15T21:14:08.657
9

I'm going through a C++ quiz. And came across the following code - it's illegal, but I can't understand why. Can anyone explain why this line:

Box* b1 = s1->duplicate();

generates the compiler error, "cannot convert from Shape* to Box"? I assumed that s1->duplicate() is calling Box::duplicate() because s1 actually points to a Box - but from the compiler error it looks like it's calling Shape::duplicate().

#include <iostream>

struct Shape
{
  virtual Shape* duplicate()
  {
    return new Shape;
  }

  virtual ~Shape() {}
};

struct Box : public Shape
{
  virtual Box* duplicate()
  {
    return new Box;
  }

};

int main(int argc, char** argv) 
{ 
  Shape* s1 = new Box;

  Box* b1 = s1->duplicate();

  delete s1;
  delete b1;
  return 0; 
}
Edit
Report

1 Answer

9

Shape::duplicates() returns a Shape*, which isn't a Box*. The runtime type you actually return has nothing to do with it. How could the compiler know that the Shape* returned actually points to a Box?

Edit: Think about this:

struct Shape
{
  virtual Shape* duplicate()
  {
    return new Shape;
  }

  virtual ~Shape() {}
};

struct Box : public Shape
{
  virtual Box* duplicate()
  {
    return new Box;
  }

};

struct Sphere : public Shape
{
  virtual Sphere* duplicate()
  {
    return new Sphere;
  }

};

Shape* giveMeABoxOrASpehere()
{
    if ( rand() % 2 )
       return new Box;
    else
       return new Sphere;
}

//
Shape* shape = giveMeABoxOrASphere();
// What does shape->duplicate() return?

Box* shape = giveMeABoxOrASphere();
// shoud this compile?
answered 2012-08-15T21:17:53.010

Your Answer