Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert from shared_ptr<derived> to shared_ptr<base> when returning from a function?

Tags:

c++

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.

like image 763
CowZow Avatar asked Oct 27 '25 11:10

CowZow


2 Answers

From your error message it appears that you used private or protected inheritance between Vehicle and Boat rather than public.

like image 142
Mark B Avatar answered Oct 29 '25 00:10

Mark B


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

like image 45
Wojtek Surowka Avatar answered Oct 29 '25 01:10

Wojtek Surowka