Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private using declaration of base constructor is not private

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?

like image 560
wally Avatar asked May 03 '18 21:05

wally


People also ask

What is the scope of 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).

What is protected constructor in c#?

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.

Can you make a constructor private in CPP?

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 .

What is the use of using declaration in C++?

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 .


1 Answers

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.

like image 53
Justin Avatar answered Sep 21 '22 13:09

Justin