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.
Inheritance

In the previous examples, we dealt with classes that are not polymorphic. This is not often the case. Much of the time, we will be wrapping polymorphic classes and class hierarchies related by inheritance. We will often have to write Boost.Python wrappers for classes that are derived from abstract base classes.

Consider this trivial inheritance structure:

    struct Base { virtual ~Base(); };
    struct Derived : Base {};

And a set of C++ functions operating on Base and Derived object instances:

    void b(Base*);
    void d(Derived*);
    Base* factory() { return new Derived; }

We've seen how we can wrap the base class Base:

    class_<Base>("Base")
        /*...*/
        ;

Now we can inform Boost.Python of the inheritance relationship between Derived and its base class Base. Thus:

    class_<Derived, bases<Base> >("Derived")
        /*...*/
        ;

Doing so, we get some things for free:

  1. Derived automatically inherits all of Base's Python methods (wrapped C++ member functions)
  2. If Base is polymorphic, Derived objects which have been passed to Python via a pointer or reference to Base can be passed where a pointer or reference to Derived is expected.

Now, we shall expose the C++ free functions b and d and factory:

    def("b", b);
    def("d", d);
    def("factory", factory);

Note that free function factory is being used to generate new instances of class Derived. In such cases, we use return_value_policy<manage_new_object> to instruct Python to adopt the pointer to Base and hold the instance in a new Python Base object until the the Python object is destroyed. We shall see more of Boost.Python call policies later.

    // Tell Python to take ownership of factory's result
    def("factory", factory,
        return_value_policy<manage_new_object>());