fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4. #include <utility>
  5.  
  6. // forward declarations of the base class and a helper function
  7. class CAnimal;
  8. void caller(CAnimal* a);
  9.  
  10. // base class with small extensions
  11. struct CAnimal {
  12. CAnimal() { mf = std::bind(caller, this); }
  13. virtual void soundsLike() { std::cout<<"Base function\n"; }
  14.  
  15. // this will act as a virtual function
  16. void makeNoice() { mf(this); }
  17. std::function<void (CAnimal*)> mf;
  18. };
  19.  
  20. // a helper function to call the real virtual function
  21. void caller(CAnimal* a) {a->soundsLike();}
  22.  
  23. // the actual animals
  24. struct CDog: public CAnimal {
  25. virtual void soundsLike() { std::cout<<"Woof\n"; }
  26. };
  27.  
  28. struct CCat: public CAnimal {
  29. virtual void soundsLike() { std::cout<<"Miau\n"; }
  30. };
  31.  
  32. int main()
  33. {
  34. // the animals
  35. CDog dog;
  36. CCat cat;
  37.  
  38. // the vector
  39. std::vector<CAnimal> animalList;
  40. animalList.push_back(dog);
  41. animalList.push_back(cat);
  42.  
  43. // calling the fake virtual
  44. animalList[0].makeNoice();
  45. animalList[1].makeNoice();
  46. }
  47.  
  48.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Woof
Miau