Dynamic cast a pointer to a child class unique pointer to pointer of parent class unique pointer

42 Views Asked by At

I have a Parent and Child class and would like to dynamic cast a pointer to a std::unique_ptr<Child> into a pointer to a std::unique_ptr<Parent> has shown in the code below. However when trying to do so I get the compilation error

error: 'std::__1::unique_ptr<Child, std::__1::default_delete<Child> >' is not polymorphic

If instead I do not use the dynamic_cast (see the commented line in the code below) it works. I would like to understand if it would be possible to use the dynamic_cast, and if yes what should I modify for it to work

Many thanks in advance for your help.

#include <iostream>
#include <memory> 

class Parent{
  public:
    Parent(){
    }
    virtual ~Parent(){
      std::cout << "Deleter of Parent class" << std::endl; 
    }
};

class Child: public Parent {
  public:
    Child(){
    }
    virtual ~Child(){
      std::cout << "Deleter of Child class" << std::endl; 
    }
};

int main(){
  std::unique_ptr<Child> myUniquePtr = std::make_unique<Child>();
  std::unique_ptr<Parent>* ptrToUniquePtr = dynamic_cast<std::unique_ptr<Parent>*>( &myUniquePtr ); // Does not work 
  // std::unique_ptr<Parent>* ptrToUniquePtr = (std::unique_ptr<Parent>*) ( &myUniquePtr ); // Works 
  
  return 0; 
}

0

There are 0 best solutions below