Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 inheriting constructors and access modifiers

Assuming the following layout:

class Base { protected:     Base(P1 p1, P2 p2, P3 p3);  public:     virtual void SomeMethod() = 0; }  class Derived : public Base { public:     using Base::Base;  public:     virtual void SomeMethod() override; }; 

Should I be able to specify Derived's constructor as public here? VC++ gives the following error:

cannot access protected member declared in class 'Derived'
compiler has generated 'Derived::Derived' here [points to the using Base::Base line]
see declaration of 'Derived'

i.e. it's ignoring the access modifier above the inherited constructor.

Is this a limitation of the feature? It doesn't make any sense for the Base class to have a public constructor, as it can never be instantiated directly (due to the pure virtual method).

like image 987
Mark Ingram Avatar asked Jan 09 '14 09:01

Mark Ingram


People also ask

Can we use access modifiers with constructor?

Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called package or friendly). Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract , final , native , static , or synchronized .

Can you inherit constructors?

No, constructors cannot be inherited in Java. In inheritance sub class inherits the members of a super class except constructors. In other words, constructors cannot be inherited in Java therefore, there is no need to write final before constructors.

Is it possible to inherit constructor in C++?

To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them. Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.

Can a class constructor be inherited?

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.


1 Answers

According to 12.9/4, "Inheriting constructors", when saying using X::X,

A constructor so declared has the same access as the corresponding constructor in X.

So the inherited constructor is also protected.

like image 84
Kerrek SB Avatar answered Oct 08 '22 13:10

Kerrek SB