#include <memory>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
/// The baseclass providing the method you want to call in derived classes.
class Base {
public:
explicit Base(const string& name)
: m_name(name)
{
}
private:
void private_method(const string& msg) // <= This is the method you want to call
{
cout << "Private method of " << m_name
<< " called with message: " << msg << endl;
}
protected:
static void call_private_method(Base& base_obj, const string& msg)
{
base_obj.private_method(msg);
}
private:
const string m_name;
};
/// A subclass providing some name.
class Foo : public Base {
public:
explicit Foo()
: Base("Foo")
{
}
};
/// Another subclass with another name.
class Bar : public Base {
public:
explicit Bar()
: Base("Bar")
{
}
};
/// Subclass that needs to call `private_method' on other subclasses of `Base`
class Accessor : public Base {
public:
explicit Accessor()
: Base("Accessor")
, m_objs()
{
m_objs.emplace_back(make_unique<Foo>());
m_objs.emplace_back(make_unique<Bar>());
}
void call_em_out()
{
for(const auto& it : m_objs){
call_private_method(*it, "success!");
}
}
private:
vector<unique_ptr<Base>> m_objs;
};
int main() {
Accessor accessor;
accessor.call_em_out();
return 0;
}
I2luY2x1ZGUgPG1lbW9yeT4KI2luY2x1ZGUgPHZlY3Rvcj4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKLy8vIFRoZSBiYXNlY2xhc3MgcHJvdmlkaW5nIHRoZSBtZXRob2QgeW91IHdhbnQgdG8gY2FsbCBpbiBkZXJpdmVkIGNsYXNzZXMuCmNsYXNzIEJhc2UgewpwdWJsaWM6CglleHBsaWNpdCBCYXNlKGNvbnN0IHN0cmluZyYgbmFtZSkKCQk6IG1fbmFtZShuYW1lKQoJewoJfQoJCnByaXZhdGU6Cgl2b2lkIHByaXZhdGVfbWV0aG9kKGNvbnN0IHN0cmluZyYgbXNnKSAvLyA8PSBUaGlzIGlzIHRoZSBtZXRob2QgeW91IHdhbnQgdG8gY2FsbAoJewoJCWNvdXQgPDwgIlByaXZhdGUgbWV0aG9kIG9mICIgPDwgbV9uYW1lIAoJCQk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