The using
declaration for the base constructor is private, but the class can still be constructed. Why?
Accessibility works differently for the operator[]
's using
declaration which must be public.
#include <vector>
template<typename T>
class Vec : std::vector<T>
{
private:
using std::vector<T>::vector; // Works, even if private. Why?
public:
using std::vector<T>::operator[]; // must be public
};
int main(){
Vec<int> vec = {2, 2};
auto test = vec[1];
}
What if I wanted the constructor to be private? Could it be done with a using
declaration?
Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions, or to introduce enumerators into namespaces, block, and class scopes (since C++20).
A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories.
Typically, constructors have public accessibility so that code outside the class definition or inheritance hierarchy can create objects of the class. But you can also declare a constructor as protected or private . Constructors may be declared as inline , explicit , friend , or constexpr .
A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A .
Using-declarations for base class constructors keep the same accessibility as the base class, regardless of the accessibility of the base class. From [namespace.udecl]:
A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored
emphasis added
In plain English, from cppreference:
It has the same access as the corresponding base constructor.
If you want the "inherited" constructors to be private, you have to manually specify the constructors. You cannot do this with a using-declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With