fork download
  1. #include <iostream>
  2.  
  3. struct A {
  4. int i;
  5. virtual void describe() {
  6. std::cout << "A:" << i << std::endl;
  7. }
  8. };
  9. struct B : public A {
  10. char c;
  11. virtual void describe() override {
  12. // Assume a 'B' wants to also output the A stuff.
  13. std::cout << "B:" << c << ":";
  14. A::describe();
  15. }
  16. };
  17. struct C : public B {
  18. float f;
  19. virtual void describe() override {
  20. // Assume a 'C' wants to also output the B stuff and A stuff.
  21. std::cout << "C:" << f << ":";
  22. B::describe();
  23. }
  24. };
  25.  
  26. #include <vector>
  27.  
  28. int main() {
  29. std::vector<A*> bar;
  30. A a;
  31. a.i = 10;
  32. B b;
  33. b.i = 22;
  34. b.c = 'b';
  35. C c;
  36. c.i = 5;
  37. c.c = 'X';
  38. c.f = 123.456;
  39. bar.push_back(&a);
  40. bar.push_back(&b);
  41. bar.push_back(&c);
  42. for (size_t i = 0; i < bar.size(); ++i) {
  43. bar[i]->describe();
  44. }
  45. }
  46.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
A:10
B:b:A:22
C:123.456:B:X:A:5