jeudi 5 novembre 2020

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;
}

Aucun commentaire:

Enregistrer un commentaire