Search code examples
c++c++14shared-ptrprotected

c++ 14 (VS 2015) shared_ptr with protected inheritance - no suitable user defined conversion


I'm getting a strange compilation error when using shared pointer with protected inheritance. The below simple code doesn't compile and gives error "no suitable user defined conversion" but it works with public inheritance. Not sure why, could anyone please explain?

class ioptionpricer
{
public:
    virtual std::shared_ptr<ioptionpricer> clone() const = 0;
    virtual void doSomething() const = 0;
    virtual ~ioptionpricer() = default;
};

class optionpricer : protected ioptionpricer
{
public:
    std::shared_ptr<ioptionpricer> clone() const
    {
        return std::make_shared<optionpricer>(*this);
    }
};

Solution

  • When the inheritance is private (or protected) then one cannot cast derived* to base* outside of the class (or derived classes for protected inheritance).

    In case of conversion from shared_ptr<derived> to shared_ptr<base>, the conversion from derived* to base* happens somewhere in implementation of the template shared_ptr<T>. So, with private/protected inheritance it won't fly. Unless you declare shared_ptr to be a friend.

    Either way just use public inheritance in these situations, it is pointless to make it private or protected in such situations.