fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct A {
  6. virtual ~A() {}; // to make A and its descendents polymorphic, you need at least one virtual function
  7. };
  8. struct B : A {
  9. void foo () { cout<<"this is a B object: foo!"<<endl; }
  10. };
  11. struct C : A {};
  12.  
  13. int main() {
  14. vector<A*> va;
  15. va.push_back (new A);
  16. va.push_back (new B);
  17. va.push_back(new C);
  18. for (auto x : va) {
  19. auto maybe = dynamic_cast<B*>(x);
  20. if (maybe) // yes, it's a B*
  21. maybe->foo();
  22. else cout << "still not a B"<<endl;
  23. }
  24. return 0;
  25. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
still not a B
this is a B object: foo!
still not a B