fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct A { virtual ~A() {} };
  5. struct B : public A { void put(int n) { cout << n << endl; } };
  6. struct C : public A { void put(float f) { cout << f << endl; } };
  7.  
  8. int main() {
  9. A *objects[2];
  10. objects[0] = new B;
  11. objects[1] = new C;
  12. for (A *a : objects) {
  13. if (auto *b = dynamic_cast<B*>(a)) {
  14. b->put(10);
  15. }
  16. else if (auto *c = dynamic_cast<C*>(a)) {
  17. c->put(3.14);
  18. }
  19. }
  20. for (A *a : objects) {
  21. delete a;
  22. }
  23. return 0;
  24. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
10
3.14