[C++-sig] Re: Containers for derived classes

David Abrahams dave at boost-consulting.com
Wed Aug 6 15:54:07 CEST 2003


abeyer at uni-osnabrueck.de writes:

> I would like to do the following:
>
> In C++:
> Class "C" is a container holding objects of type "A".
>
> In Python:
> Class "B" is derived from class "A" and instances of "B" get stored in
> containers of type "C".
>
> When I store objects of Type B in C, they get 'downcasted' to A. 

That direction is normally referred to as "up", and if you're really
holding A's by value, you're "slicing", not "upcasting".

> Objects
> returned from the container are hence no longer of type B, but of type A.
> Of course I could store the original boost::python::object somewhere.
> However, the FAQ says there are more elegant ways by using
> boost::shared_ptr:
> "When a shared_ptr<X> is converted back to Python, the library checks to
> see if it's one of those "Python object managers" and if so just returns
> the original Python object."
>
> I have played with it, but I had no luck so far.

What did you do?  Please post some code which illustrates.

> Has anyone an example using shared_ptr that fits my purpose?

If you make C a container of shared_ptr<A>, it should just work.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list