Constructors

| Constructors

Our previous example didn't have any explicit constructors. Since `World` is declared as a plain struct, it has an implicit default constructor. Boost.Python exposes the default constructor by default, which is why we were able to write

`

        >>> planet = hello.World()

`

We may wish to wrap a class with a non-default constructor. Let us build on our previous example:

`

        struct World
        {
            World(std::string msg): msg(msg) {} // added constructor
            void set(std::string msg) { this->msg = msg; }
            std::string greet() { return msg; }
            std::string msg;
        };

`

This time `World` has no default constructor; our previous wrapping code would fail to compile when the library tried to expose it. We have to tell `class_<World>` about the constructor we want to expose instead.

`

        #include <boost/python.hpp>
        using namespace boost::python;

        BOOST_PYTHON_MODULE(hello)
        {
            class_<World>("World", init<std::string>())
                .def("greet", &World::greet)
                .def("set", &World::set)
            ;
        }

`

`init<std::string>()` exposes the constructor taking in a `std::string` (in Python, constructors are spelled "`"__init__"`").

We can expose additional constructors by passing more `init<...>`s to the `def()` member function. Say for example we have another World constructor taking in two doubles:

`

        class_<World>("World", init<std::string>())
            .def(init<double, double>())
            .def("greet", &World::greet)
            .def("set", &World::set)
        ;

`

On the other hand, if we do not wish to expose any constructors at all, we may use `no_init` instead:

`

        class_<Abstract>("Abstract", no_init)

`

This actually adds an `__init__` method which always raises a Python RuntimeError exception.

Copyright © 2002-2003 David Abrahams
Copyright © 2002-2003 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.