I need to copy-construct an object simultaneously changing it\'s type to another class being a member of the same class-hierarchy. I\'ve read about polymorphic copy-constructors
c2 = (Child2*)c1->clone();
Here is a serious bug, and the c-style cast hides the bug.
If you use C++-style cast, then it will not hide the bug, and you will know it. In this case, the C++-style cast is : dynamic_cast
. Use it to discover the bug yourself.
As it is clear from the code thatc1-clone()
creates a clone of c1
whose type is Child1*
and clone()
returns a pointer of type Base*
(after upcasting from Child1*
), which you're trying to down-cast to Child2*
. The cast should fail if you use proper cast : dynamic_cast
.