pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

How to call into protected constructors?

Open nbpatel opened this issue 9 years ago • 3 comments

class A {}

template < typename T > class B : public A {

protected: B():A(...) . . . }

My classes are templated.. and i am using this https://developer.lsst.io/coding/python_wrappers_for_cpp_with_pybind11.html as a reference to wrap my C++ code. New to pybind, so any help appreciated :)

Compilation error: error: ‘namespace_x::namespace_y::B< T > ::B() [with T = float]’ is protected

nbpatel avatar Nov 06 '17 22:11 nbpatel

How would you create a B instance in C++? For example, if you have some factory function, you could use something like: .def(py::init([]() { return B::factory(); })). As it is, it looks non-creatable.

Alternatively, if the class is polymorphic, one way you could do this is to define a trampoline class that wraps B, exposes its constructor, and tells pybind to always create a MyB instance when a B is constructed from Python:

class A {};
class B : public A {
protected B() : A() {}
};

// Later, in pybind binding code:
class MyB : public B {
public:
    MyB() : B() {}
};
py::class_<B, MyB>(m, "B")
    .def(py::init_alias<B>());

jagerman avatar Nov 07 '17 02:11 jagerman

There is indeed a factory function that does that :). I got around this problem. I just call the factory function. But what you suggested sounds correct too. Thanks for the quick response.

Also, how do i deal with non-public destructors and shared_ptr. I know the tutorial has a section explaining non public destructors and unique_ptr. I tried py::nodelete with shared_ptr and it doesn't work. PS: Not sure if this issue is the right place to ask this question :)

nbpatel avatar Nov 08 '17 05:11 nbpatel

I am also having this issue. When i use a shared ptr and py::nodelete i get an error "template argument 2 is invalid"

gagelarsen avatar Apr 19 '18 16:04 gagelarsen