diff --git a/docs/advanced/classes.rst b/docs/advanced/classes.rst index db782ab5eac..71fbf2cb0c6 100644 --- a/docs/advanced/classes.rst +++ b/docs/advanced/classes.rst @@ -144,6 +144,29 @@ a virtual method call. >>> call_go(c) u'meow! meow! meow! ' +If you are defining a custom constructor in a derived Python class, you *must* +ensure that you explicitly call the bound C++ constructor using ``__init__``, +*regardless* of whether it is a default constructor or not. Otherwise, the +memory for the C++ portion of the instance will be left uninitialized, which +could do nasty things, such as give you a corrupted ``vtable``. + +Here is an example: + +.. code-block:: python + + class Dachschund(Dog): + def __init__(self, name): + Dog.__init__(self) # Without this, a segfault may occur. + self.name = name + def bark(self): + return "yap!" + +Note that a direct ``__init__`` constructor *should be called*, and ``super()`` +should not be used. For simple cases of linear inheritance, ``super()`` +may work, but once you begin mixing Python and C++ multiple inheritance, +things will fall apart due to differences between Python's MRO and C++'s +mechanisms. + Please take a look at the :ref:`macro_notes` before using this feature. .. note::