in below scenario, I need to invoke child class B function (fun1) from Base class A shared pointer returned by setup function and for the same have used dynamic_cast_pointer so that derived class shared_ptr object can be assigned to Base class shared_ptr but during compilation I am not allowed to do so. Can anybody suggest how to achieve this behaviour
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
void fun() {cout<<"A"<<endl;}
};
class B : public A
{
public:
void fun1() {cout<<"B" <<endl;}
};
shared_ptr<A> setup(shared_ptr<A> ptr = nullptr )
{
if(!ptr)
{
ptr = make_shared<A> ();
}
ptr.get()->fun();
return ptr;
}
int main() {
auto ptr = std::dynamic_pointer_cast <B> (setup());
ptr->fun1(); // Doesn't compile
}
CodePudding user response:
I presume the question is cut down from the real problem.
Presuming you're not expecting this example to work at runtime (you are casting a pointer to A as a pointer to B when it's an instance of A - so you're in undefined behaviour territory), the issue is that you have no virtual methods. The compiler tells you this:
error: 'A' is not polymorphic
When you intend to use pointers to a base class, you need to have virtual destructors (personally I always use them as a matter of course).
See demo: https://godbolt.org/z/qe6jPrhsa
Here you can see a modified example demonstrating that you're in Undefined Behaviour territory... https://godbolt.org/z/harzoP946