I did a test. I have a template function with a template parameter of a class's member method pointer. When I pass a protected member method pointer there, the template function can call the protected method. Is this reasonable? I think it also works for private methods.
Thanks to the deleted comments for my code. I simplify my code and find the reason.
template<class T, void (T::*f)()>
void foo(T t)
{
(t.*f)();
}
class A
{
public:
void g() { foo<A, &A::f>(*this); } // ok for access in class A scope
protected:
void f() {}
};
int main()
{
A a;
a.g();
//foo<A, &A::f>(a); // error, no access to the protected method in this scope.
return 0;
}
The compiler is smart!
If you deliberately hand a thing out to someone, they can access it.
This is no different from the fact that you can pass e.g. a private int member as a parameter to wherever you want, even by reference so they can modify it.
In a sense, protected/private prevents theft, not gifts.