I want to know why I can't downcast the base class to a derived class with the type std::shared_ptr<>

Asked 1 years ago, Updated 1 years ago, 305 views

Question details

As per the title, I would like to know how to downcast the base class to the derived class using the std::shared_ptr<> smart pointer.

What I checked

From the reference site

 std::shared_ptr<Derived>delivered=std::make_shared<Derived>();
std::shared_ptr<base>base=std::dynamic_pointer_cast<base>(derived);

With reference to , Derived is replaced by base, and base is replaced by base, which should only be inherited from the base instead of the base, but the following error appears:

Error

$make
g++-c-MMD-MP src/Main.cpp-obj/Main.o-I./../src-I~/Library-I~/Library/freetype 
File included from /usr/include/c++/9/memory: 81,
                 from src/Main.cpp:2:
/usr/include/c++/9/bits/shared_ptr.h:Instantation of'std::shared_ptr<_Tp>std::dynamic_pointer_cast(conststd::shared_ptr<_Tp>&) [with_Tp=der;_Up='base:']
src/Main.cpp:42:62:required from here
/usr/include/c++/9/bits/shared_ptr.h:510:23: error: cannot dynamic_cast ‘(& __r)->std::shared_ptr<base>::<anonymous>.std::__shared_ptr<base, __gnu_cxx::_S_atomic>::get()’ (of type ‘using element_type = std::remove_extent<base>::type*’ {aka ‘class base*’}) to type ‘using element_type = using element_type = std::remove_extent<der>::type*' {aka'classder*'} (source type is not polymorphic)
  510 | if (auto*__p=dynamic_cast<typename_Sp::element_type*>(_r.get()))
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
make:*** [Makefile:15:obj/Main.o] Error 1

What I checked

std::shared_ptr<der>b=std::dynamic_pointer_cast<der>(d); commenting out eliminates the error, so the last line below is the reason for the error.

Reference Site

(dynamic_cast part of shared_ptr): https://komorinfo.com/blog/cast-of-smart-pointers/ #toc_id_2

What do you want to know

Want to know how to cast from base to derived using smart pointer std::shared_ptr<>

Source code (bottom)

#include<iostream>
# include <memory>

class base
{
public:
    base()
    {
        std::cout<<"base()"<<std::endl;
    }
};

classder —public base
{
public:

    der() —base()
    {
        std::cout<<"der()"<<std::endl;
    }
};




int main()
{

    std::shared_ptr<base>d=std::make_shared<der>();
    std::shared_ptr<der>b=std::dynamic_pointer_cast<der>(d);


    return 0;
}

c++

2022-12-25 00:53

1 Answers

Error Message

source type is not polymorphic

and so on.
In other words, the base class must contain some virtual function in order for the derived classes of the base class to behave in many ways.
For example, virtual~base{}.

The same thing happens with dynamic_cast without using std::shared_ptr/std::dynamic_pointer_cast.


2022-12-25 01:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.