How can a derived C++ class clone itself via a base pointer?

后端 未结 6 739
旧巷少年郎
旧巷少年郎 2021-01-13 09:34

Here\'s what I\'m trying to do (this code doesn\'t work):

class Base
{
    virtual Base *clone() { return new Base(this); }
    virtual void ID() { printf(\"         


        
6条回答
  •  花落未央
    2021-01-13 10:07

    You're slicing the class in Base bp = &d; (this constructs a new base bp from the derived-ptr.)

    Try Base* bp = &d; instead. (i.e. create a pointer of Base type to the Derived object.)

提交回复
热议问题