subtle C++ inheritance error with protected fields

后端 未结 6 937
無奈伤痛
無奈伤痛 2020-12-03 02:38

Below is a subtle example of accessing an instance\'s protected field x. B is a subclass of A so any variable of type B is also of type A. Why can B::foo() access b\'s x fie

6条回答
  •  我在风中等你
    2020-12-03 03:12

    Why can B::foo() access b's x field, but not a's x field?

    A protected member can only be accessed by other members of the same class (or derived classes).

    b->x points to a protected member of an instance of class B (through inheritance), so B::foo() can access it.

    a->x points to a protected member of an instance of class A, so B::foo() cannot access it.

提交回复
热议问题