Skip to content

When overriding...the missing __init__ to parent very common bug.  #96

Open

Description

@damienmarchal
No description provided.

Activity

  1. marques-bruno commented on Sep 11, 2019

    @marques-bruno
    Contributor

    From the pybind11 documentation:

    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 will generally leave the C++ instance in an invalid state and cause undefined behavior if the C++ instance is subsequently used.

    Here is an example:

    class Dachschund(Dog):
        def __init__(self, name):
            Dog.__init__(self) # Without this, undefind behavior may occur if the C++ portions are referenced.
            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.

    I don't think it's avoidable

  2. damienmarchal commented on Sep 11, 2019

    @damienmarchal
    MemberAuthor

    I know..seems hard to avoid but having a clean way to warn users how to fix the crash would be an already nice objective.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions