John Zwinck
John Zwinck

Reputation: 249444

Can a static method in a derived class call a protected constructor in C++?

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?

Upvotes: 21

Views: 2220

Answers (1)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99655

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.

Upvotes: 11

Related Questions