[C++-sig] problem returning polymorphic shared_ptr instances

Matt Bendiksen matt_boost at perceptiveautomation.com
Wed Jan 12 18:03:44 CET 2011

I'm stumped on a problem encountered when trying to return a derived instance via a shared_ptr to python. The python instance is always shown as a base class and not the subclass that was created, as if the instance was sliced.

	struct A {
	struct B : A {
	shared_ptr<A> get_a_or_b_instance(bool returnB) {
	    return shared_ptr<A>(returnB ? new B() : new A());
	def("get_a_or_b_instance", get_a_or_b_instance);
	class_<A, boost::shared_ptr<A> >("A", init<>())
	class_<B, bases<A>, boost::noncopyable>("B", init<>())

And the Python result is always a type A object:

	>>> type(app.get_a_or_b_instance(False))
	<class 'app.A'>

	>>> type(app.get_a_or_b_instance(True))
	<class 'app.A'>

Where I would expect the derived instance type B returned from the second call.

I'm using Boost 1.42.0.

Thanks in advance for any help.

Matt Bendiksen

More information about the Cplusplus-sig mailing list