#include <iostream>
class A {
protected:
void foo()
{}
};
class B : public A {
public:
void bar()
{
std::cout << (&A::foo) << std::endl;
}
};
int main()
{
B b;
b.bar();
}
Here I am trying to get address of protected member function of base class. I am getting this error.
main.cpp: In member function ‘void B::bar()’:
main.cpp:5: error: ‘void A::foo()’ is protected
main.cpp:13: error: within this context
make: *** [all] Error 1
Changing foo to public works. Also printing &B::foo
works. Can you please explain why we can't get address of protected member function of base class?
B
is allowed to access protected members ofA
as long as the access is performed through an object of typeB
. In your example you're trying to accessfoo
throughA
, and in that context it is irrelevant whetherB
derives fromA
or not.From N3337, §11.4/1 [class.protected]
Your example is very similar to the code in
D2::mem
, which shows that trying to form a pointer to a protected member throughB
instead ofD2
is ill-formed.Seems I found the answer. If we could get pointer of member function we can call it for other objects of type
A
(notthis
) which is not allowed.It is not allowed to call protected member function in derived classes for objects other than
this
. Getting pointer would violent that.We can do something like this:
I was curious and tried the following example:
Actually, I see that
&A::foo
==&B::foo
, so for protected member of base class you can use derived class member to take address. I suppose in case of virtual functions this will not work