Copying derived entities using only base class pointers, (without exhaustive testing!) - C++

后端 未结 4 1153
感情败类
感情败类 2020-12-02 17:15

Given a base class that is inherited by plethora of derived classes, and a program structure that requires you manage these via base class pointers to each entity. Is there

4条回答
  •  自闭症患者
    2020-12-02 17:41

    Note that you don't need the static_cast there. Derived* converts to Base* implicitly. You absolutely shouldn't use a dynamic_cast for that, as Ken Wayne suggests, since the concrete type is known at compile time, and the compiler can tell you if the cast is not allowed.

    As for the approach, this pattern is standard enough to be built in to C# and Java as ICloneable and Object.clone(), respectively.

    Edit:

    ... or is there a better, even neater way of doing this?

    You could use a "self-parameterized base class", which saves you implementing the clone() function each time. You just need to implement the copy constructor:

    #include 
    
    struct CloneableBase {
        virtual CloneableBase* clone() const = 0;
    };
    
    
    template
    struct Cloneable : CloneableBase {
        virtual CloneableBase* clone() const {
           return new Derived(static_cast(*this));
        }
    };
    
    
    struct D1 : Cloneable {
        D1() {}
        D1(const D1& other) {
            std::cout << "Copy constructing D1\n";
        }
    };
    
    struct D2 : Cloneable {
        D2() {}
        D2(const D2& other) {
            std::cout << "Copy constructing D2\n";
        }
    };
    
    
    int main() {
        CloneableBase* a = new D1();
        CloneableBase* b = a->clone();
        CloneableBase* c = new D2();
        CloneableBase* d = c->clone();
    }
    

提交回复
热议问题