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

后端 未结 4 1170
感情败类
感情败类 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:38

    template 
    Base* CopyDerived(const T& other) {
      T* derivedptr = new T(other);
      Base* baseptr = dynamic_cast(derivedptr);
      if(baseptr != NULL)
        return baseptr;
      delete derivedptr;
      // If this is reached, it is because T is not derived from Base
      // The exception is just an example, handle in whatever way works best
      throw "Invalid types in call to Copy";
    }
    

    This only requires a publicly accessible copy constructor in each derived class you wish to copy.

提交回复
热议问题