21

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?

John Zwinck
  • 239,568
  • 38
  • 324
  • 436

1 Answers1

11

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.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
  • 2
    +1 As for the rationale, `protected` provides access to the `A` subobject inside `B`, not to *any* `A`. Another example would be `struct C : A { static void break_invariants( B& b ) { b.protected_member_from_A = 5; } };`, which could *potentially* break the invariants held in `B`. – David Rodríguez - dribeas Aug 30 '11 at 20:14
  • David: it's interesting that you say that, because GCC *does* allow accessing (modifying) protected static data members of the base class from a static method in the derived class. Do you think *that* is a bug in GCC then? – John Zwinck Aug 30 '11 at 21:29
  • @Kirill: does that part of the standard apply only to constructors? Because it seems that normal named methods and data members can be accessed in a similar way under GCC. – John Zwinck Aug 30 '11 at 23:12
  • 1
    @John Zwinck, no, it's not only about constructors. Probably you use static members or you use normal named methods via *this* (implicitly). – Kirill V. Lyadvinsky Aug 31 '11 at 04:23