Search code examples
c++inheritanceprivate-members

c++ Only inherit public constructors


I am trying to inherit a constructor from a base class, but I am getting the error: C2876: 'Poco::ThreadPool' : not all overloads are accessible.

namespace myNamespace{

    class ThreadPool : public Poco::ThreadPool{
        using Poco::ThreadPool::ThreadPool;  // inherits constructors
    };

}

Poco::ThreadPool has 3 constructors, 2 public ones both with default initialised arguments, and 1 private one.

How can I only inherit the public constructors?

I am not using c++11.


Solution

  • If you are not using C++11 or later, you can't inherit all base constructors with a single using declaration.

    The old way pre-C++11 was to create a corresponding c'tor in the derived class for every c'tor in the base we wanted to expose. So for example:

    struct foo {
      int _i;
      foo(int i = 0) : _i(i) {}
    };
    
    struct bar : private foo {
      bar() : foo() {} // Use the default argument defined in foo
      bar(int i) : foo(i) {} // Use a user supplied argument
    };
    

    If you still want to have a c'tor with a default argument, you can do that too:

    struct baz : private foo {
      baz(int i = 2) : foo(i) {} // We can even change what the default argument is
    };