fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. struct A {
  7. virtual void showb() {cout<<"showa"<<endl;} // if no virtual, dynamic_cast will not compile
  8. };
  9. struct B : A {
  10. void showb() {cout<<"showb"<<endl;}
  11. };
  12.  
  13. int main() {
  14.  
  15. list <shared_ptr<A>> container;
  16. shared_ptr<B> b = shared_ptr<B>(new B);
  17. container.push_back(b);
  18.  
  19. auto it = container.begin();
  20. shared_ptr<B> aB = static_pointer_cast<B>(*it);
  21. aB->showb();
  22.  
  23. container.push_back(make_shared<A>());
  24. for (auto i = container.begin(); i!=container.end(); i++) {
  25. shared_ptr<B> spb = dynamic_pointer_cast<B>(*i);
  26. if (spb)
  27. spb->showb(); // at least one virtual function
  28. else cout << "the pointer was not to a B";
  29. }
  30.  
  31. // your code goes here
  32. return 0;
  33. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
showb
showb
the pointer was not to a B