Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class B;
  4.  
  5. class A {
  6. friend class B;
  7. private:
  8. int x;
  9. };
  10.  
  11. class B {
  12. static void print(const A& a) {
  13. // x is private, but B is a friend of A, so it's fine
  14. std::cout << a.x << std::endl;
  15. }
  16. };
  17.  
  18. int main() {
  19. B b;
  20. A a;
  21. b.print(a);
  22. return 0;
  23. }
  24.  
  25. #include <iostream>
  26.  
  27. class A {
  28. private:
  29. int x;
  30. };
  31.  
  32. class B : public A {
  33. void print() {
  34. // error A::x is private!
  35. std::cout << A::x << std::endl;
  36. }
  37. };
  38.  
  39. int main() {
  40. B b;
  41. b.print();
  42. return 0;
  43. }
  44.  
  45. #include <iostream>
  46.  
  47. class A {
  48. protected:
  49. int x;
  50. };
  51.  
  52. class B : public A {
  53. void print() {
  54. // A::x is protected, but B inherits from A, so it's fine
  55. std::cout << A::x << std::endl;
  56. }
  57. };
  58.  
  59. int main() {
  60. B b;
  61. b.print();
  62. A a;
  63. // error a::x is protected and can only be accessed from A or from any class which inherits from A
  64. // std::cout << a.x << std::endl;
  65. return 0;
  66. }
  67.  
  68. class A
  69. {
  70. int a1;
  71. };
  72.  
  73. class B : public A
  74. {
  75. int b1 ;
  76. };
  77.  
  78. class B : public A
  79. {
  80. int b1 ;
  81. A *a;
  82.  
  83. void foo()
  84. {
  85. std::cout << a->a1; --> possible because B is a friend of A
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement