fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class A {
  5. int num;
  6. public:
  7. int get_num() const { cout<<"get_num for "<<(void*)this<<endl; return num; }
  8. };
  9.  
  10. class B : public A {
  11. void foob() { int x = get_num(); }
  12. };
  13.  
  14. class C { // won't inherit from A anymore
  15. const A& base; // instead keeps a reference to A
  16. void fooc() { int x = base.get_num(); }
  17. public:
  18. explicit C(const A* b) : base(*b) { } // receive reference to A
  19. void show_oops() { fooc(); }
  20. };
  21.  
  22. class D : public B, public C {
  23. void food() { int x = get_num(); }
  24. public:
  25. D() : C(this) { } // pass "this" pointer
  26. void show() { food(); }
  27. };
  28.  
  29. int main() {
  30. D d;
  31. cout<<"d is "<<(void*)&d<<endl;
  32. d.show();
  33. d.show_oops();
  34. D d2=d;
  35. cout<<"d2 is "<<(void*)&d2<<endl;
  36. d2.show();
  37. d2.show_oops();
  38.  
  39. // your code goes here
  40. return 0;
  41. }
Success #stdin #stdout 0s 16048KB
stdin
Standard input is empty
stdout
d is  0x7fffe0fd11a0
get_num for 0x7fffe0fd11a0
get_num for 0x7fffe0fd11a0
d2 is  0x7fffe0fd11b0
get_num for 0x7fffe0fd11b0
get_num for 0x7fffe0fd11a0