CowZow
CowZow

Reputation: 1424

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

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.

Upvotes: 4

Views: 3026

Answers (3)

Massimo Costa
Massimo Costa

Reputation: 1860

you can create a shared_ptr to Vehicle and use it

boost::shared_ptr<Vehicle> create_vehicle(Environment e, Cost c) 
{
    boost::shared_ptr<Vehicle> vehicle;
    if (e.is_water()) {
        Boat *boat = new Boat();
        boat->set_location("USA");
        boat->set_environment(e);

        vehicle.reset(boat); // Assign the pointer to the result

    } else if (e.is_land()) {
        ...
    }
    return vehicle;
}

Upvotes: 0

Wojtek Surowka
Wojtek Surowka

Reputation: 21013

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

Upvotes: 2

Mark B
Mark B

Reputation: 96311

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

Upvotes: 5

Related Questions