[C++-sig] Newcomer - constructors not working as I'd expect

Andrew Pontzen app26 at ast.cam.ac.uk
Sun Apr 9 23:24:13 CEST 2006


Hi - apologies in advance if this is a question covered elsewhere. I did 
as thorough a search as I could for information before posting.

I am using boost.python (from boost package 1_33_1) to expose some C++ 
classes. I have a problem with constructors - here is a simple test case:


   class test1 {
   public:
     virtual string getText() const {
       return "Hello test1";
     }
     virtual ~test1() { } ;
   };

   class test2 : public test1 {
   public:
     virtual string getText() const {
       return "Hello test2";
     }
     virtual ~test2() { } ;
   };


   class test3 : public test2 {
   public:

     test3(const test1 &basedon) : ourobj(basedon) { };

     virtual string getText() const {
       return ourobj.getText();
     }

     const test1 & ourobj;

     virtual ~test3() { } ;
   };


   void printMessage(test1 & obj) {
     cout << obj.getText() << endl;
   }



   BOOST_PYTHON_MODULE(testme)
   {


     def("pm", &printMessage);

     class_<test1>("test1",init<>());
     class_<test2, bases<test1> >("test2",init<>());
     class_<test3, bases<test2> >("test3",init<test1>());
   }


In Python, things happen as expected until constructing a test3 object:

>>> a=testme.test1()
>>> b=testme.test2()
>>> testme.pm(a)
Hello test1
>>> testme.pm(b)
Hello test2
>>> c=testme.test3(a)
>>> testme.pm(c)
Segmentation fault


Using gdb, it seems the C++ constructor for test3 is never called, so the 
getText() call accesses an invalid reference.

I don't understand why this should be - clearly I've missed something!

TIA for any help.

Andrew

--
Andrew Pontzen
app26 at ast.cam.ac.uk

Institute of Astronomy
Madingley Road
Cambridge
CB3 0HA
UK



More information about the Cplusplus-sig mailing list