Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of boost. Click here for the latest Boost documentation.
Deriving a Python Class

Continuing, we can derive from our base class Base in Python and override the virtual function in Python. Before we can do that, we have to set up our class_ wrapper as:

    class_<Base, BaseWrap, boost::noncopyable>("Base")
        ;

Otherwise, we have to suppress the Base class' no_init by adding an __init__() method to all our derived classes. no_init actually adds an __init__ method that raises a Python RuntimeError exception.

    >>> class Derived(Base):
    ...     def f(self):
    ...         return 42
    ...

Cool eh? A Python class deriving from a C++ class!

Let's now make an instance of our Python class Derived:

    >>> derived = Derived()

Calling derived.f():

    >>> derived.f()
    42

Will yield the expected result. Finally, calling calling the free function call_f with derived as argument:

    >>> call_f(derived)
    42

Will also yield the expected result.

Here's what's happening:

  1. call_f(derived) is called in Python
  2. This corresponds to def("call_f", call_f);. Boost.Python dispatches this call.
  3. int call_f(Base& b) { return b.f(); } accepts the call.
  4. The overridden virtual function f of BaseWrap is called.
  5. call_method<int>(self, "f"); dispatches the call back to Python.
  6. def f(self): return 42 is finally called.