classes.rst (11986:c12e4625ab56) classes.rst (12037:d28054ac6ec9)
1Classes
2#######
3
4This section presents advanced binding code for classes and it is assumed
5that you are already familiar with the basics from :doc:`/classes`.
6
7.. _overriding_virtuals:
8

--- 65 unchanged lines hidden (view full) ---

74 /* Inherit the constructors */
75 using Animal::Animal;
76
77 /* Trampoline (need one for each virtual function) */
78 std::string go(int n_times) override {
79 PYBIND11_OVERLOAD_PURE(
80 std::string, /* Return type */
81 Animal, /* Parent class */
1Classes
2#######
3
4This section presents advanced binding code for classes and it is assumed
5that you are already familiar with the basics from :doc:`/classes`.
6
7.. _overriding_virtuals:
8

--- 65 unchanged lines hidden (view full) ---

74 /* Inherit the constructors */
75 using Animal::Animal;
76
77 /* Trampoline (need one for each virtual function) */
78 std::string go(int n_times) override {
79 PYBIND11_OVERLOAD_PURE(
80 std::string, /* Return type */
81 Animal, /* Parent class */
82 go, /* Name of function */
82 go, /* Name of function in C++ (must match Python name) */
83 n_times /* Argument(s) */
84 );
85 }
86 };
87
88The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
89functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
90a default implementation. There are also two alternate macros
91:func:`PYBIND11_OVERLOAD_PURE_NAME` and :func:`PYBIND11_OVERLOAD_NAME` which
92take a string-valued name argument between the *Parent class* and *Name of the
83 n_times /* Argument(s) */
84 );
85 }
86 };
87
88The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
89functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
90a default implementation. There are also two alternate macros
91:func:`PYBIND11_OVERLOAD_PURE_NAME` and :func:`PYBIND11_OVERLOAD_NAME` which
92take a string-valued name argument between the *Parent class* and *Name of the
93function* slots. This is useful when the C++ and Python versions of the
93function* slots, which defines the name of function in Python. This is required
94when the C++ and Python versions of the
94function have different names, e.g. ``operator()`` vs ``__call__``.
95
96The binding code also needs a few minor adaptations (highlighted):
97
98.. code-block:: cpp
99 :emphasize-lines: 4,6,7
100
101 PYBIND11_PLUGIN(example) {

--- 8 unchanged lines hidden (view full) ---

110 .def(py::init<>());
111
112 m.def("call_go", &call_go);
113
114 return m.ptr();
115 }
116
117Importantly, pybind11 is made aware of the trampoline helper class by
95function have different names, e.g. ``operator()`` vs ``__call__``.
96
97The binding code also needs a few minor adaptations (highlighted):
98
99.. code-block:: cpp
100 :emphasize-lines: 4,6,7
101
102 PYBIND11_PLUGIN(example) {

--- 8 unchanged lines hidden (view full) ---

111 .def(py::init<>());
112
113 m.def("call_go", &call_go);
114
115 return m.ptr();
116 }
117
118Importantly, pybind11 is made aware of the trampoline helper class by
118specifying it as an extra template argument to :class:`class_`. (This can also
119specifying it as an extra template argument to :class:`class_`. (This can also
119be combined with other template arguments such as a custom holder type; the
120order of template types does not matter). Following this, we are able to
121define a constructor as usual.
122
120be combined with other template arguments such as a custom holder type; the
121order of template types does not matter). Following this, we are able to
122define a constructor as usual.
123
124Bindings should be made against the actual class, not the trampoline helper class.
125
126.. code-block:: cpp
127
128 py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
129 animal
130 .def(py::init<>())
131 .def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
132
123Note, however, that the above is sufficient for allowing python classes to
124extend ``Animal``, but not ``Dog``: see ref:`virtual_and_inheritance` for the
125necessary steps required to providing proper overload support for inherited
126classes.
127
128The Python session below shows how to override ``Animal::go`` and invoke it via
129a virtual method call.
130

--- 50 unchanged lines hidden (view full) ---

181
182.. code-block:: cpp
183
184 class Animal {
185 public:
186 virtual std::string go(int n_times) = 0;
187 virtual std::string name() { return "unknown"; }
188 };
133Note, however, that the above is sufficient for allowing python classes to
134extend ``Animal``, but not ``Dog``: see ref:`virtual_and_inheritance` for the
135necessary steps required to providing proper overload support for inherited
136classes.
137
138The Python session below shows how to override ``Animal::go`` and invoke it via
139a virtual method call.
140

--- 50 unchanged lines hidden (view full) ---

191
192.. code-block:: cpp
193
194 class Animal {
195 public:
196 virtual std::string go(int n_times) = 0;
197 virtual std::string name() { return "unknown"; }
198 };
189 class Dog : public class Animal {
199 class Dog : public Animal {
190 public:
191 std::string go(int n_times) override {
192 std::string result;
193 for (int i=0; i<n_times; ++i)
194 result += bark() + " ";
195 return result;
196 }
197 virtual std::string bark() { return "woof!"; }

--- 17 unchanged lines hidden (view full) ---

215 class PyDog : public Dog {
216 public:
217 using Dog::Dog; // Inherit constructors
218 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Dog, go, n_times); }
219 std::string name() override { PYBIND11_OVERLOAD(std::string, Dog, name, ); }
220 std::string bark() override { PYBIND11_OVERLOAD(std::string, Dog, bark, ); }
221 };
222
200 public:
201 std::string go(int n_times) override {
202 std::string result;
203 for (int i=0; i<n_times; ++i)
204 result += bark() + " ";
205 return result;
206 }
207 virtual std::string bark() { return "woof!"; }

--- 17 unchanged lines hidden (view full) ---

225 class PyDog : public Dog {
226 public:
227 using Dog::Dog; // Inherit constructors
228 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Dog, go, n_times); }
229 std::string name() override { PYBIND11_OVERLOAD(std::string, Dog, name, ); }
230 std::string bark() override { PYBIND11_OVERLOAD(std::string, Dog, bark, ); }
231 };
232
233.. note::
234
235 Note the trailing commas in the ``PYBIND11_OVERLOAD`` calls to ``name()``
236 and ``bark()``. These are needed to portably implement a trampoline for a
237 function that does not take any arguments. For functions that take
238 a nonzero number of arguments, the trailing comma must be omitted.
239
223A registered class derived from a pybind11-registered class with virtual
224methods requires a similar trampoline class, *even if* it doesn't explicitly
225declare or override any virtual methods itself:
226
227.. code-block:: cpp
228
229 class Husky : public Dog {};
230 class PyHusky : public Husky {
240A registered class derived from a pybind11-registered class with virtual
241methods requires a similar trampoline class, *even if* it doesn't explicitly
242declare or override any virtual methods itself:
243
244.. code-block:: cpp
245
246 class Husky : public Dog {};
247 class PyHusky : public Husky {
231 using Dog::Dog; // Inherit constructors
248 public:
249 using Husky::Husky; // Inherit constructors
232 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Husky, go, n_times); }
233 std::string name() override { PYBIND11_OVERLOAD(std::string, Husky, name, ); }
234 std::string bark() override { PYBIND11_OVERLOAD(std::string, Husky, bark, ); }
235 };
236
237There is, however, a technique that can be used to avoid this duplication
238(which can be especially helpful for a base class with several virtual
239methods). The technique involves using template trampoline classes, as
240follows:
241
242.. code-block:: cpp
243
244 template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
250 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Husky, go, n_times); }
251 std::string name() override { PYBIND11_OVERLOAD(std::string, Husky, name, ); }
252 std::string bark() override { PYBIND11_OVERLOAD(std::string, Husky, bark, ); }
253 };
254
255There is, however, a technique that can be used to avoid this duplication
256(which can be especially helpful for a base class with several virtual
257methods). The technique involves using template trampoline classes, as
258follows:
259
260.. code-block:: cpp
261
262 template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
263 public:
245 using AnimalBase::AnimalBase; // Inherit constructors
246 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, AnimalBase, go, n_times); }
247 std::string name() override { PYBIND11_OVERLOAD(std::string, AnimalBase, name, ); }
248 };
249 template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
264 using AnimalBase::AnimalBase; // Inherit constructors
265 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, AnimalBase, go, n_times); }
266 std::string name() override { PYBIND11_OVERLOAD(std::string, AnimalBase, name, ); }
267 };
268 template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
269 public:
250 using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
251 // Override PyAnimal's pure virtual go() with a non-pure one:
252 std::string go(int n_times) override { PYBIND11_OVERLOAD(std::string, DogBase, go, n_times); }
253 std::string bark() override { PYBIND11_OVERLOAD(std::string, DogBase, bark, ); }
254 };
255
256This technique has the advantage of requiring just one trampoline method to be
257declared per virtual method and pure virtual method override. It does,

--- 110 unchanged lines hidden (view full) ---

368 class MyClass {
369 private:
370 ~MyClass() { }
371 };
372
373 /* ... binding code ... */
374
375 py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
270 using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
271 // Override PyAnimal's pure virtual go() with a non-pure one:
272 std::string go(int n_times) override { PYBIND11_OVERLOAD(std::string, DogBase, go, n_times); }
273 std::string bark() override { PYBIND11_OVERLOAD(std::string, DogBase, bark, ); }
274 };
275
276This technique has the advantage of requiring just one trampoline method to be
277declared per virtual method and pure virtual method override. It does,

--- 110 unchanged lines hidden (view full) ---

388 class MyClass {
389 private:
390 ~MyClass() { }
391 };
392
393 /* ... binding code ... */
394
395 py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
376 .def(py::init<>)
396 .def(py::init<>())
377
397
398.. _implicit_conversions:
399
378Implicit conversions
379====================
380
381Suppose that instances of two types ``A`` and ``B`` are used in a project, and
382that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
383could be a fixed and an arbitrary precision number type).
384
385.. code-block:: cpp

--- 31 unchanged lines hidden (view full) ---

417
418Static properties
419=================
420
421The section on :ref:`properties` discussed the creation of instance properties
422that are implemented in terms of C++ getters and setters.
423
424Static properties can also be created in a similar way to expose getters and
400Implicit conversions
401====================
402
403Suppose that instances of two types ``A`` and ``B`` are used in a project, and
404that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
405could be a fixed and an arbitrary precision number type).
406
407.. code-block:: cpp

--- 31 unchanged lines hidden (view full) ---

439
440Static properties
441=================
442
443The section on :ref:`properties` discussed the creation of instance properties
444that are implemented in terms of C++ getters and setters.
445
446Static properties can also be created in a similar way to expose getters and
425setters of static class attributes. It is important to note that the implicit
426``self`` argument also exists in this case and is used to pass the Python
427``type`` subclass instance. This parameter will often not be needed by the C++
428side, and the following example illustrates how to instantiate a lambda getter
429function that ignores it:
447setters of static class attributes. Note that the implicit ``self`` argument
448also exists in this case and is used to pass the Python ``type`` subclass
449instance. This parameter will often not be needed by the C++ side, and the
450following example illustrates how to instantiate a lambda getter function
451that ignores it:
430
431.. code-block:: cpp
432
433 py::class_<Foo>(m, "Foo")
434 .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
435
436Operator overloading
437====================

--- 35 unchanged lines hidden (view full) ---

473 py::module m("example", "pybind11 example plugin");
474
475 py::class_<Vector2>(m, "Vector2")
476 .def(py::init<float, float>())
477 .def(py::self + py::self)
478 .def(py::self += py::self)
479 .def(py::self *= float())
480 .def(float() * py::self)
452
453.. code-block:: cpp
454
455 py::class_<Foo>(m, "Foo")
456 .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
457
458Operator overloading
459====================

--- 35 unchanged lines hidden (view full) ---

495 py::module m("example", "pybind11 example plugin");
496
497 py::class_<Vector2>(m, "Vector2")
498 .def(py::init<float, float>())
499 .def(py::self + py::self)
500 .def(py::self += py::self)
501 .def(py::self *= float())
502 .def(float() * py::self)
503 .def(py::self * float())
481 .def("__repr__", &Vector2::toString);
482
483 return m.ptr();
484 }
485
486Note that a line like
487
488.. code-block:: cpp

--- 146 unchanged lines hidden ---
504 .def("__repr__", &Vector2::toString);
505
506 return m.ptr();
507 }
508
509Note that a line like
510
511.. code-block:: cpp

--- 146 unchanged lines hidden ---