Forum Replies Created

Viewing 1 post (of 1 total)
  • Author
    Posts
  • in reply to: (Classic) Factory Pattern Obsolete #636875
    Lukas Klein
    Participant
        Up
        1
        Down
        ::

        Thank you. I had to look up covariant return types, in case someone else stumbles across this, here is a example:

        This works:

        class Base {
        public:
            virtual Base* clone() const {
                return new Base(*this);
            }
        };
        
        class Derived : public Base {
        public:
            Derived* clone() const override {
                return new Derived(*this);
            }
        };
        
        int main() {
            Base* b = new Derived();
            Base* b_clone = b->clone();
        
            delete b;
            delete b_clone;
            return 0;
        }

        and this does not work:

        class Base {
        public:
            virtual std::unique_ptr<Base> clone() const {
                return std::make_unique<Base>(*this);
            }
            virtual ~Base() = default;
        };
        
        class Derived : public Base {
        public:
            std::unique_ptr<Derived> clone() const override {
                return std::make_unique<Derived>(*this);
            }
        };
        
        int main() {
            std::unique_ptr<Base> b = std::make_unique<Derived>();
            std::unique_ptr<Base> b_clone = b->clone();
            return 0;
        }
      Viewing 1 post (of 1 total)