Search code examples
c++python-3.xboost-python

Boost.Python - error with parametrized constructor


I have got a toy class from tutorialspoint in a file test.h:

class Box {
   public:

      Box(int l, int b, int h)
      {
        length = l;
        breadth = b;
        height = h;       
      }

      double getVolume(void) {
         return length * breadth * height;
      }
      void setLength( double len ) {
         length = len;
      }
      void setBreadth( double bre ) {
         breadth = bre;
      }
      void setHeight( double hei ) {
         height = hei;
      }

   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};

In the another file I have:

BOOST_PYTHON_MODULE(test)
{
  namespace python = boost::python;

  python::class_<Box>("Box")
    .def("setLength",  &Box::setLength )
    .def("setBreadth", &Box::setBreadth)
    .def("setHeight",  &Box::setHeight )
    .def("getVolume",  &Box::getVolume );
}

When I compile this code I get the error message about the Box class constructor:

/usr/include/boost/python/object/value_holder.hpp:133:13: error: no matching function for call to ‘Box::Box()’
             BOOST_PP_REPEAT_1ST(N, BOOST_PYTHON_UNFORWARD_LOCAL, nil)
             ^

What am I missing?

Do I need to write the constructor paramaters in BOOST_PYTHON_MODULE()? If so, how to do it?


Solution

  • You dont have a default constructor and you are missing the one you declared:

    BOOST_PYTHON_MODULE(test) {
      namespace python = boost::python;
    
      python::class_<Box>("Box", boost::python::init<int, int, int>())
        .def("setLength",  &Box::setLength )
        .def("setBreadth", &Box::setBreadth)
        .def("setHeight",  &Box::setHeight )
        .def("getVolume",  &Box::getVolume );
    }