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;
}
Shape::duplicates()returns aShape*, which isn’t aBox*. The runtime type you actually return has nothing to do with it. How could the compiler know that theShape*returned actually points to aBox?Edit: Think about this: