Question

how to use pure virtual function for Multiple inhertiance by using boost python. Error i got are that 'Derived1' cannot instaniate abstract class. and 'Derived2' cannot instantiate abstract class. this code is working if there is only one derived class but more than one derived classs its not working. thanks for help.

class Base
{
  public:
   virtual int test1(int a,int b) = 0;
   virtual int test2 (int c, int d) = 0;
   virtual ~Base() {}
 };

class Derived1
  : public Base
 {
   public:
   int test1(int a, int b) { return a+b; }
};

class Derived2
 : public Base
{
  public:
  int test2(int c, int d) { return c+d; }
};
struct BaseWrap
  : Base, python::wrapper<Base>
{
  int test1(int a , int b) 
  {
     return this->get_override("test")(a, b);
   }
  int test2(int c ,int d)
   {
     return this->get_override("test")(c, d);
    }
};

BOOST_PYTHON_MODULE(example) 
{
  python::class_<BaseWrap, boost::noncopyable>("Base")
   .def("test1", python::pure_virtual(&BaseWrap::test1))
   .def("test2", python::pure_virtual(&BaseWrap::test2))
   ;

  python::class_<Derived1, python::bases<Base> >("Derived1")
   .def("test1", &Derived1::test1)
   ;

   python::class_<Derived2, python::bases<Base> >("Derived2")
   .def("test2", &Derived2::test2)
   ;   
}
Was it helpful?

Solution

The error messages indicate that neither Derived1 nor Derived2 can be instantiated, as they are abstract classes:

  • Derived1 has a pure virtual function: int Base::test2(int, int).
  • Derived2 has a pure virtual function: int Base::test1(int, int).

When either of these are exposed via boost::python::class_, a compiler error should occur. class_'s HeldType defaults to the type being exposed, and the HeldType is constructed within a Python object. Hence, python::class_<Derived1, ...> will instantiate Boost.Python templates that attempt to create an object with a dynamic type of Derived1, resulting in the compiler error.

This error does not present itself with BaseWrap, as BaseWrap implements all pure virtual functions. The boost::python::pure_virtual() function specifies that Boost.Python will raise a "pure virtual called" exception during dispatch if the function has not been overridden in either C++ or Python.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top