Search code examples
c++c++11unique-ptr

convert base class unique_ptr to derived class unique_ptr


I need to convert my base class unique_ptr to a derived class unique_ptr so that I can access some of the functions of the derived class.

The code I have throws error. What is going on wrong here?

#include <iostream>
#include <memory>

class Base
{};

class Derived : public Base
{
  public:
  Derived(int x):_x(x){}
  
  int oneDerivedClassFunction()
  {    return _x;  }
  
  private: 
    int _x;
};

int main()
{
    std::unique_ptr<Base> basePtr;
    basePtr.reset(new Derived(10));
    
    auto der = std::unique_ptr<Derived>(dynamic_cast<Derived*>(basePtr.release())); // error here!
    printf("%d", der->oneDerivedClassFunction());
    return 0;
}

Solution

  • The problem is that dynamic_cast can't be used on non-polymorphic types.

    Depending on your intent, you could make Base polymorphic, e.g.

    class Base
    {
      public:
      virtual ~Base() {}
    };
    

    LIVE

    Or you can use static_cast instead, if you're sure about the conversion result.

    LIVE