fork download
  1. #include <memory>
  2. #include <vector>
  3. #include <iostream>
  4. #include <string>
  5. using namespace std;
  6.  
  7. /// The baseclass providing the method you want to call in derived classes.
  8. class Base {
  9. public:
  10. explicit Base(const string& name)
  11. : m_name(name)
  12. {
  13. }
  14.  
  15. private:
  16. void private_method(const string& msg) // <= This is the method you want to call
  17. {
  18. cout << "Private method of " << m_name
  19. << " called with message: " << msg << endl;
  20. }
  21. protected:
  22. static void call_private_method(Base& base_obj, const string& msg)
  23. {
  24. base_obj.private_method(msg);
  25. }
  26.  
  27. private:
  28. const string m_name;
  29. };
  30.  
  31. /// A subclass providing some name.
  32. class Foo : public Base {
  33. public:
  34. explicit Foo()
  35. : Base("Foo")
  36. {
  37. }
  38. };
  39.  
  40. /// Another subclass with another name.
  41. class Bar : public Base {
  42. public:
  43. explicit Bar()
  44. : Base("Bar")
  45. {
  46. }
  47. };
  48.  
  49. /// Subclass that needs to call `private_method' on other subclasses of `Base`
  50. class Accessor : public Base {
  51. public:
  52. explicit Accessor()
  53. : Base("Accessor")
  54. , m_objs()
  55. {
  56. m_objs.emplace_back(make_unique<Foo>());
  57. m_objs.emplace_back(make_unique<Bar>());
  58. }
  59.  
  60. void call_em_out()
  61. {
  62. for(const auto& it : m_objs){
  63. call_private_method(*it, "success!");
  64. }
  65. }
  66.  
  67. private:
  68. vector<unique_ptr<Base>> m_objs;
  69. };
  70.  
  71. int main() {
  72. Accessor accessor;
  73. accessor.call_em_out();
  74. return 0;
  75. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Private method of Foo called with message: success!
Private method of Bar called with message: success!