Reputation: 1691
There are two external class (A and B)that I cannot change. I would like to access protected member of the class A:: doSomething in C (which I can do edit). Is there any way to access it. I understand its not good practice but I did not find any other way of doing it.
// External code starts
struct A {
friend class B;
protected:
void doSomething() {
std::cout << "A" << std::endl;
}
};
struct B {
protected:
void doSomething() {
A a;
a.doSomething();
}
};
// External code ends
// This will not compile as doSomething is a protected member.
struct C : B {
protected:
void doSomethingElse() {
A a;
a.doSomething();
}
};
Upvotes: 3
Views: 133
Reputation: 96071
Friendship is not transitive, so inheriting from B
doesn't help with this.
Inherit from A
and form a pointer-to-member to doSomething
:
struct Helper : A
{
static constexpr auto ptr = &Helper::doSomething;
};
Use that pointer to call a function on a
:
void doSomethingElse()
{
A a;
(a.*Helper::ptr)();
}
Upvotes: 2