This code works with clang but g++ says:
error: ‘A::A()’ is protected
class A
{
protected:
A() {}
};
class B : public A
{
static A f() { return A(); } // GCC claims this is an error
};
Which compiler is right?
Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.
The only way to cause a protected constructor to be called is to derive from the class and have the derived class delegate to it or to have a static method create it or some other internal method.
Explanation: Protected access modifier means that constructor can be accessed by child classes of the parent class and classes in the same package.
Protecting a constructor prevents the users from creating the instance of the class, outside the package. During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only. Outer class and interface cannot be protected.
g++ is right.
The C++ Standard §11.5/1 says that "<...> the access must be through a pointer to, reference to, or object of the derived class itself <...>". In case of constructors, this means that B
is allowed to call the protected constructor of A
only in order to construct its own base subobject.
Check this related issue in g++. It was closed as not a bug.
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