You may have wondered why for the herd() function in Exercise 15-4 we asked you to switch from using Animal shared_ptrs to raw Sheep* pointers. Shouldn’t that have been shared_ptr instead? The main problem is that you cannot simply cast a shared_ptr to a shared_ptr. These are unrelated types as far as the compiler is concerned. But you are correct; it probably would’ve been better to use shared_ptr, and we were probably underestimating your capabilities there. All you really need to know is that to cast between shared_ptr and shared_ptr you mustn’t use the built-in dynamic_cast and static_cast operators, but instead the std::dynamic_ pointer_cast and std::static_pointer_cast Standard Library functions defined in the module. For instance, let shared_animal be a shared_ ptr. Then dynamic_pointer_cast(shared_animal) results in a shared_ptr. If shared_animal points to a Sheep, the resulting smart pointer will refer to that Sheep; if not, it will contain nullptr. Adapt the solution of Exercise 15-4 to properly use smart pointers everywhere.
Already registered? Login
Not Account? Sign up
Enter your email address to reset your password
Back to Login? Click here