fork download
  1. #include <iostream>
  2.  
  3. struct Base; struct Derived; // First case: Base is protected.
  4. struct B; struct D; // Second case: Function is protected.
  5.  
  6. // -----
  7.  
  8. // Base is protected.
  9. struct Base {
  10. void func() { std::cout << "Hi.\n"; }
  11. };
  12.  
  13. struct Derived : protected Base {
  14. void heya() { std::cout << "Direct call says: "; return func(); }
  15.  
  16. void ahey() {
  17. static Derived* ptr = this;
  18. std::cout << "Through static pointer says: ";
  19. return ptr->func();
  20. }
  21. };
  22.  
  23. // -----
  24.  
  25. // Function is protected.
  26. struct B {
  27. protected:
  28. void func() { std::cout << ".iH\n"; }
  29. };
  30.  
  31. struct D : public B {
  32. void heya() { std::cout << "Direct call says: "; return func(); }
  33.  
  34. void ahey() {
  35. static D* ptr = this;
  36. std::cout << "Through static pointer says: ";
  37. return ptr->func();
  38. }
  39. };
  40.  
  41. // -----
  42.  
  43. int main() {
  44. // Base is protected.
  45. Derived der;
  46.  
  47. der.heya();
  48. der.ahey();
  49.  
  50. // -----
  51.  
  52. // Function is protected.
  53. D d;
  54.  
  55. d.heya();
  56. d.ahey();
  57.  
  58. // -----
  59.  
  60. // Through a different instance?
  61. Derived{}.ahey();
  62. D{}.ahey();
  63. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Direct call says: Hi.
Through static pointer says: Hi.
Direct call says: .iH
Through static pointer says: .iH
Through static pointer says: Hi.
Through static pointer says: .iH