fork download
  1.  
  2. #include <iostream>
  3.  
  4. class Base
  5. {
  6. private:
  7. int m_value {};
  8.  
  9. public:
  10. Base(int value)
  11. : m_value{ value }
  12. {
  13. }
  14.  
  15. friend std::ostream& operator<< (std::ostream& out, const Base& b)
  16. {
  17. out << "In Base\n";
  18. out << b.m_value << '\n';
  19. return out;
  20. }
  21. };
  22.  
  23. class Derived : public Base
  24. {
  25. public:
  26. Derived(int value)
  27. : Base{ value }
  28. {
  29. }
  30.  
  31. friend std::ostream& operator<< (std::ostream& out, const Derived& d)
  32. {
  33. out << "In Derived\n";
  34. // static_cast Derived to a Base object, so we call the right version of operator<<
  35. out << static_cast<const Base&>(d);
  36. return out;
  37. }
  38. };
  39.  
  40. int main()
  41. {
  42. Derived derived { 7 };
  43.  
  44. std::cout << derived << '\n';
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0.01s 5460KB
stdin
Standard input is empty
stdout
In Derived
In Base
7