Access to protected member through member-pointer: is it a hack?

前端 未结 4 964
抹茶落季
抹茶落季 2020-12-07 16:48

We all know members specified protected from a base class can only be accessed from a derived class own instance. This is a feature from the Standard, and this

4条回答
  •  半阙折子戏
    2020-12-07 17:09

    is it a hack?

    In similar vein to using reinterpret_cast, this can be dangerous and may potentially be a source of hard to find bugs. But it's well formed and there's no doubt whether it should work.

    To clarify the analogy: The behaviour of reinterpret_cast is also specified exactly in the standard and can be used without any UB. But reinterpret_cast circumvents the type system, and the type system is there for a reason. Similarly, this pointer to member trick is well formed according to the standard, but it circumvents the encapsulation of members, and that encapsulation (typically) exists for a reason (I say typically, since I suppose a programmer can use encapsulation frivolously).

    [Is it] a glitch somewhere in the implementation or the wording of the Standard?

    No, the implementation is correct. This is how the language has been specified to work.

    Member function of Derived can obviously access &Derived::value, since it is a protected member of a base.

    The result of that operation is a pointer to a member of Base. This can be applied to a reference to Base. Member access privileges does not apply to pointers to members: It applies only to the names of the members.


    From comments emerged another question: if Derived::f is called with an actual Base, is it undefined behaviour?

    Not UB. Base has the member.

提交回复
热议问题