Reputation: 51
I have a base class:
class Base{
public:
Base();
virtual ~Base();
.....
}
class Derived2: public Base{
public:
Derived2();
...
}
and in my main, i tried to dynamic cast boost::shared_ptr from base to derived2:
testFunction(boost:shared_ptr<Base> base){
Derived2* derived2 = dynamic_cast<Derived2*>(base);
}
Upvotes: 0
Views: 91
Reputation: 238401
The operand of a dynamic_cast is not a pointer type
how can i fix it?
By not using a non-pointer type as operand of dynamic_cast
. In other words, by using a pointer type as the operand.
You can get a pointer from a shared pointer using get
member function.
Be careful to not let this bare pointer leak to outside the scope of the function. You can trust on its validity only as long as the argument base
points to the object. Also don't attempt to take ownership of that bare pointer, since its ownership is already shared.
P.S. std::shared_ptr
has been in the standard library since C++11.
P.P.S. dynamic_cast
is a code smell.
Upvotes: 0
Reputation: 96835
Boost has dynamic_pointer_cast
:
boost::shared_ptr<Derived2> derived2 = boost::dynamic_pointer_cast<Derived2>(base);
Upvotes: 1