[C++-sig] Polymorphism with injected constructor...

Alex Mohr amohr at pixar.com
Thu Jan 5 21:03:10 CET 2006


This little test breaks if I use an injected constructor.  Base_wrap's 
call to get_override() fails.  The offending line is marked below.  If I 
comment it out, this test works.  See below for the output and expected 
output.

#include <boost/python.hpp>
#include <string>

using namespace boost::python;
using std::string;

struct Base {
     virtual ~Base() {}
     virtual string Func() { return "C++ Func"; }
};

struct Base_wrap : Base, wrapper<Base> {
     static Base_wrap *New() { return new Base_wrap(); }
     string default_Func() { return Base::Func(); }
     virtual string Func() {
         if (override func = get_override("Func"))
             return func();
         return default_Func();
     }
};

static void Test(Base *b) {
     printf("Func -> '%s'\n", b->Func().c_str());
}

BOOST_PYTHON_MODULE(Test) {
     def("Test", Test);
     class_<Base_wrap, boost::noncopyable>("Base")
         // *** Commenting out the following line fixes the test.
         .def("__init__", make_constructor(&Base_wrap::New))
         .def("Func", &Base::Func, &Base_wrap::default_Func)
         ;
}

#####
from Test import *
class Derived(Base):
     def Func(self):
         return 'Python Func'

Test(Base())
Test(Derived())
#####

Output is:
Func -> 'C++ Func'
Func -> 'C++ Func'

Expected is:
Func -> 'C++ Func'
Func -> 'Python Func'

Again, the test works correctly if I comment out the injected 
constructor.  Can anyone explain why this happens?

Thanks,

Alex




More information about the Cplusplus-sig mailing list