fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4.  
  5. class Foo {
  6. public:
  7. Foo() { format_string(); }
  8. Foo(int a) { format_string(a); }
  9.  
  10. void print() { std::cout << str; }
  11.  
  12. protected:
  13. std::string str;
  14.  
  15. void format_string(int a = 0)
  16. {
  17. std::stringstream stream;
  18. stream << "{a: " << a << "}\n";
  19. str = stream.str();
  20. }
  21. };
  22.  
  23. class Bar : public Foo {
  24. public:
  25. Bar() { format_string(); }
  26. Bar(int a, int b) { format_string(a, b); }
  27.  
  28. protected:
  29. void format_string(int a = 0, int b = 0)
  30. {
  31. std::stringstream stream;
  32. stream << "{a: " << a << ", b: " << b << "}\n";
  33. str = stream.str();
  34. }
  35. };
  36.  
  37. int main() {
  38. Foo t1 = Bar(10,10);
  39. Bar t2 = Bar(20,20);
  40. Foo *t3 = new Bar(30,30);
  41. Foo t4 = Bar(10, 20);
  42. t1.print();
  43. t2.print();
  44. t3->print();
  45. t4.print();
  46. delete t3;
  47. return 0;
  48. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
{a: 10, b: 10}
{a: 20, b: 20}
{a: 30, b: 30}
{a: 10, b: 20}