KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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; }
Tags (comma-separated)
Save Edits
Cancel