customoo.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Copyright © 2015 Hein-Pieter van Braam <hp@tmm.cx>
  2. * This work is free. You can redistribute it and/or modify it under the
  3. * terms of the Do What The Fuck You Want To Public License, Version 2,
  4. * as published by Sam Hocevar. See the COPYING file for more details.
  5. *
  6. * Text copied from http://www.firthworks.com/roger/cloak/
  7. */
  8. #include <cstddef>
  9. #include <iostream>
  10. #include <stdexcept>
  11. #include <string>
  12. #include <map>
  13. using namespace std;
  14. class object;
  15. class method {
  16. public:
  17. method(string val): _val(val) {};
  18. ~method() {};
  19. bool call() {
  20. cout << "Method: '" << _val << "'" << endl;
  21. return true;
  22. };
  23. private:
  24. string _val;
  25. };
  26. class object {
  27. friend class method;
  28. public:
  29. object() {};
  30. object(object* parent): _parent(parent) {};
  31. ~object() {
  32. for(auto i: _methods) {
  33. delete(i.second);
  34. }
  35. };
  36. bool call_method(string name) {
  37. try {
  38. method* method = _methods.at(name);
  39. return method->call();
  40. } catch (const out_of_range& e) {
  41. if(_parent) {
  42. return _parent->call_method(name);
  43. } else {
  44. cout << "No method " << name << endl;
  45. return false;
  46. }
  47. }
  48. };
  49. void add_method(string name, method* method) {
  50. _methods[name] = method;
  51. };
  52. protected:
  53. object* _parent = nullptr;
  54. map<string, method*> _methods;
  55. };
  56. int main() {
  57. object* o = new object();
  58. o->call_method("stuff");
  59. o->add_method("stuff", new method("Stuff"));
  60. o->call_method("stuff");
  61. object* p = new object(o);
  62. p->call_method("stuff");
  63. delete o;
  64. }