fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class Base {
  8. public:
  9.  
  10. Base(const string& s) {
  11. m_s = s;
  12. }
  13.  
  14. virtual ~Base() {
  15. };
  16.  
  17. friend ostream & operator <<(ostream & os, const Base & b) {
  18. b.print(os);
  19. return os;
  20. }
  21.  
  22. virtual void print(ostream & os) const {
  23. os << "Base";
  24. }
  25.  
  26. string m_s;
  27. };
  28.  
  29. class Derived : public Base {
  30. public:
  31.  
  32. Derived(const string& s, int i) : Base(s) {
  33. m_int = i;
  34. }
  35.  
  36. virtual void print(ostream & os) const {
  37. os << "Derived";
  38. }
  39.  
  40. int m_int;
  41. };
  42.  
  43. class Store {
  44. public:
  45.  
  46. Store(const string& s) {
  47. m_s = s;
  48. }
  49.  
  50. void Add(const Base& b) {
  51. cout << b << endl; //output before storing to vector
  52. v.push_back(&b);
  53. }
  54.  
  55. friend ostream & operator <<(ostream & os, const Store & x);
  56.  
  57. string m_s;
  58. vector<const Base*> v;
  59. };
  60.  
  61. ostream & operator <<(ostream & os, const Store & x) {
  62. for (auto it = x.v.cbegin(); it != x.v.cend(); ++it) {
  63. cout << *(*it) << endl;
  64. }
  65. return os;
  66. }
  67.  
  68. int main() {
  69. Store a("aaaaaaa");
  70. a.Add(Derived("abc", 5));
  71. a.Add(Derived("def", 6));
  72.  
  73. cout << endl;
  74. cout << a; //output after storing to vector
  75.  
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Derived
Derived

Base
Base