Override method with shared_ptr Base type with shared_ptr Derived type

779 Views Asked by At

I am attempting to create an abstract method for cloning classes derived from base and returning them as a shared_ptr like so:

class Base {
public:
    virtual std::shared_ptr<BaseSymbol> clone() = 0;
};
class Derived : public Base {
public:
    Derived(const Derived& derived);
    std::shared_ptr<Derived> clone();
};

This is getting me a compilation error. I know this is possible to achieve this with normal pointers, so how can I get this to work with shared pointers?

1

There are 1 best solutions below

6
Jarod42 On BEST ANSWER

covariance is only possible with pointer/reference.

For smart pointer, you have to "duplicate" the interface:

class Base {
public:
    std::shared_ptr<Base> clone() const
    {
        return std::shared_ptr<Base>(vclone());
    }

    virtual ~Base() = default;
protected:
    virtual BaseSymbol* vclone() const = 0;
};
class Derived : public Base {
public:
    Derived(const Derived& derived);

    std::shared_ptr<Derived> clone() const
    {
        return std::shared_ptr<Derived>(vclone());
    }
protected:
    Derived* vclone() const override { return new Derived(*this); }
};

CRTP might help to avoid to rewrite the same pattern.