Question

how can i called the pure virtual function in derived class by using boost python .Error i got is that cannot instantiate the abstract base class. The sample code is as :

class Base
{
public: 
    virtual int test() = 0;
};

class Derived : public Base
{
public:
    int  test()
    {
        int  a = 10;
        return a;
    }
};

struct  BaseWrap : Base, wrapper<Base>
{
    Int  test() 
    {
        return this->get_override(“test”)();
    }
};

BOOST_PYTHON_MODULE(Pure_Virtual) 
{
    Class_<BaseWrap, boost::noncopyable>(“Base”, no_init)
    .def(“test”, pure_virtual($Base::test)
    ;

    Class_<Derived, bases<Base> >(“Derived”)
    .def(“test”, &Derived::test)
    ;   
}
Was it helpful?

Solution

Pure virtual functions are invoked the same way as non-pure virtual functions. The only difference is that a function exposed as a pure virtual Python method will raise a RuntimeError when invoked.

The initial posted code has various syntax problems, so it is difficult to identify exactly what the problem is. However, here is a complete example based on the original code:

#include <boost/python.hpp>

namespace python = boost::python;

class Base
{
public:
  virtual int test() = 0;
  virtual ~Base() {}
};

class Derived
  : public Base
{
public:
  int test() { return 10; }
};

struct BaseWrap
  : Base, python::wrapper<Base>
{
  int test() 
  {
    return this->get_override("test")();
  }
};

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

  python::class_<Derived, python::bases<Base> >("Derived")
    .def("test", &Derived::test)
    ;   
}

And its usage:

>>> import example
>>> derived = example.Derived()
>>> derived.test()
10
>>> class Spam(example.Base):
...     pass
... 
>>> s = Spam()
>>> s.test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Pure virtual function called
>>> class Egg(example.Base):
...     def test(self):
...         return 42
... 
>>> e = Egg()
>>> e.test()
42

When test() is invoked on a type that inherits from example.Base but does not implement a test() method, Boost.Python will raise a RuntimeError indicating a pure virtual function has been invoked. Hence, test() on a Spam object raises an exception, where as test() on an Egg object is properly dispatched.

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