Using "use" in public to inherit a private constructor does not make it public

"using" the private member variable makes it public, but the constructor remains private. Example:

class MyClass; class Base { private: Base(float v) : m_v{v} {} float m_v; friend MyClass; }; class MyClass: public Base { public: using Super = Base; using Super::Super; // this is still private using Super::m_v; // this is public }; int main() { MyClass x{3.4f}; // error - calling a private constructor of class 'Base' (void)x.m_v; // not an error return 0; } 

Is there any other way besides writing a universal ctor like this?

 template<typename... Args> MyClass(Args&&... args) : Super(std::forward<Args>(args)...) {} 
+5
source share
1 answer

http://en.cppreference.com/w/cpp/language/using_declaration#Inheriting_constructors contains the following excerpt:

It has the same access as the corresponding base constructor. This is constexpr if the custom constructor would fulfill the requirements of the constexpr constructor. It is deleted if the corresponding base constructor is deleted or if the default default constructor is deleted (except that the construction of the base whose constructor is inherited is not taken into account). The inheritance constructor cannot be explicitly created or explicitly specialized.

It refers to an inherited constructor. I'm not sure why, but it seems your approach is explicitly forbidden. A common solution is to define a universal call divert constructor.

+1
source

Source: https://habr.com/ru/post/1266475/


All Articles