Polymorphic copy-constructor with type conversion

后端 未结 4 1573
遇见更好的自我
遇见更好的自我 2021-01-26 11:18

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

4条回答
  •  孤城傲影
    2021-01-26 11:52

    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.

提交回复
热议问题