fork download
  1. class Base
  2. {
  3. public:
  4. void foo() {} // Dummy method to clarify the example
  5. };
  6.  
  7. class PublicChild : public Base
  8. {
  9. public:
  10. void test()
  11. {
  12. foo(); // OK, we have access to Base public members
  13. static_cast<Base*>(this)->foo(); // OK
  14. }
  15. friend class PublicFriend;
  16. };
  17.  
  18. class PublicFriend
  19. {
  20. void test(PublicChild* p)
  21. {
  22. p->foo(); // OK, the method is public anyway
  23. static_cast<Base*>(p)->foo(); // OK
  24. }
  25. };
  26.  
  27. class ProtectedChild : protected Base
  28. {
  29. public:
  30. void test()
  31. {
  32. foo(); // OK, we have access to Base public members
  33. static_cast<Base*>(this)->foo(); // OK
  34. }
  35. friend class ProtectedFriend;
  36. };
  37.  
  38. class ProtectedFriend
  39. {
  40. void test(ProtectedChild* p)
  41. {
  42. p->foo(); // OK, because we are a friend of ProtectedChild, we have the same visibility as ProtectedChild itself
  43. static_cast<Base*>(p)->foo(); // OK
  44. }
  45. };
  46.  
  47. class PrivateChild : private Base
  48. {
  49. public:
  50. void test()
  51. {
  52. foo(); // OK, we have access to Base public members
  53. static_cast<Base*>(this)->foo(); // OK
  54. }
  55. friend class PrivateFriend;
  56. };
  57.  
  58. class PrivateFriend
  59. {
  60. void test(PrivateChild* p)
  61. {
  62. p->foo(); // OK, because we are a friend of PrivateChild, we have the same visibility as PrivateChild itself
  63. static_cast<Base*>(p)->foo(); // OK
  64. }
  65. };
  66.  
  67. int main()
  68. {
  69. Base b;
  70. b.foo(); // OK: public method
  71.  
  72. PublicChild p1;
  73. p1.foo(); // OK: public inheritance makes Base::foo public
  74. static_cast<Base>(p1).foo(); // OK
  75.  
  76. ProtectedChild p2;
  77. // p2.foo(); // error: protected inheritance makes Base::foo protected
  78. // static_cast<Base>(p2).foo(); // error
  79.  
  80. PrivateChild p3;
  81. // p3.foo(); // error: private inheritance makes Base::foo private
  82. // static_cast<Base>(p3).foo(); // error
  83.  
  84. return 0;
  85. }
Success #stdin #stdout 0s 4388KB
stdin
Standard input is empty
stdout
Standard output is empty