[C++-sig] What determines whether a returned pointer is downcast or not?

Mark Ivey zovirl at zovirl.com
Mon Aug 13 01:17:42 CEST 2007


What determines whether a returned pointer is downcast or not?  The  
simple example below prints <class 'test.Base'>.  But if I make  
Base::f virtual and recompile, then it prints <class 'test.Type1'>.   
Why doesn't it work for the non-virtual case?

I'm actually trying to wrap some 3rd-party code so I'm stuck with the  
non-virtual case.  What other options do I have for doing the  
downcast?  The typical C++ way to use the 3rd-party code is to  
dynamic_cast the pointer coming back from the factory, but I haven't  
been able to figure what the python equivalent is.  I suppose I could  
make a large collection of wrapper functions to do the dynamic_cast  
and return the correct pointer type, but I'm hoping for a more  
elegant solution.  Does one exist?


Python:

import test
x = test.factory(1)
print type(x)

C++:

class Base { void f(){}; };
class Type1: public Base { void x(){} };
class Type2: public Base { void y(){} };

Base *factory(int type)
{
   if (type == 1)
     return new Type1();
   else
     return new Type2();
}

BOOST_PYTHON_MODULE(test)
{
   class_<Base>("Base");
   class_<Type1, bases<Base> >("Type1");
   class_<Type2, bases<Base> >("Type2");
   def("factory", factory,  
return_value_policy<reference_existing_object>());
}



More information about the Cplusplus-sig mailing list