Can I overload init from C++ side in pybind11?

145 views Asked by At

If in C++ a class had an overloaded constructor:

class MyClass {
    std::string name;
public:
    MyClass(){};
    MyClass(std::string name_){ name = name_;}
};

how do I expose this to python? Can I use py::overload_cast and py::init together?

Currently I expose the first one:

PYBIND11_MODULE(ex_module, module_handle){
    module_handle.doc() = "ex class";

    py::class_<MyClass>(module_handle, "PyEx")
        .def(py::init<>())
        ;
}

(Note that I'm using C++20 and python >=3.10)

I want to be able to do:

new_obj = PyEx()
new_obj = PyEx("blah")

Currently, PyEx("blah") isn't throwing any errors, but it's also not really passing blah into the C++ constructor. I check this by adding a print statement in the second constructor.

Edit: simplified the question.

1

There are 1 answers

0
pptaszni On BEST ANSWER

There is no need to use any overload_cast tricks, because exposing the constructor is different than exposing a method where you pass the pointer to member function. You just need to define your single argument constructor after (or before) the default one:

    py::class_<MyClass>(module_handle, "PyEx")
        .def(py::init<>())
        .def(py::init<std::string>())
        ;