fork download
  1. #include <iostream>
  2.  
  3. using std::cout;
  4. using std::endl;
  5.  
  6. class Base
  7. {
  8. public:
  9. int x;
  10.  
  11. Base() : x(42)
  12. {
  13. }
  14.  
  15. virtual void PrintSomething()
  16. {
  17. cout << "Base::PrintSomething x=" << x << endl;
  18. }
  19. };
  20.  
  21. class Derived : public Base
  22. {
  23. public:
  24. int y;
  25.  
  26. Derived() : y(-1)
  27. {
  28. x = 0;
  29. }
  30.  
  31. virtual void PrintSomething()
  32. {
  33. cout << "Derived::PrintSomething x=" << x << " y=" << y << endl;
  34. }
  35. };
  36.  
  37. int main (int argc, char *argv[])
  38. {
  39. Base bValue;
  40. Derived dValue;
  41.  
  42. bValue.PrintSomething();
  43. dValue.PrintSomething();
  44.  
  45. Base *bPointer1 = &bValue;
  46. Base *bPointer2 = &dValue;
  47.  
  48. // call PrintSomething virtually
  49. bPointer1->PrintSomething();
  50. bPointer2->PrintSomething();
  51.  
  52. Base bCopy1 = bValue;
  53. Base bCopy2 = dValue; // dValue is sliced
  54.  
  55. // call PrintSomething non-virtually
  56. bCopy1.PrintSomething();
  57. bCopy2.PrintSomething();
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
Base::PrintSomething x=42
Derived::PrintSomething x=0 y=-1
Base::PrintSomething x=42
Derived::PrintSomething x=0 y=-1
Base::PrintSomething x=42
Base::PrintSomething x=0