Lets say we have an abstract class called Vehicle. A bunch of classes will inherit from Vehicle such as Boat, Car, Truck, etc.
I want to create a function which returns me a pointer to a vehicle given certain parameters that I pass in. I don't need access to the underlying Vehicle. I have something like this so far:
boost::shared_ptr<Vehicle> create_vehicle(Environment e, Cost c) {
if (e.is_water()) {
boost::shared_ptr<Boat> boat(new Boat());
boat->set_location("USA");
boat->set_environment(e);
...
return boat; // How should I return the shared pointer here?
// I get an error for doing this
// "Vehicle is an inaccessible base of boat"
} else if (e.is_land()) {
...
}
}
How can I return the shared_ptr of derived when the return value of the function is a shared_ptr? Is casting necessary or is there a way to do without casting? I guess I could also just return the derived class by value but I do not want to make another copy of the vehicle when I return it.
From your error message it appears that you used private or protected inheritance between Vehicle and Boat rather than public.
You need to use static_pointer_cast - it is in a way equivalent to static_cast for shared_pointers. Look at http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/shared_ptr.htm#functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With