This code:
class B {
protected:
void Foo(){}
}
class D : public B {
public:
void Baz() {
Foo();
}
void Bar() {
printf("%x\n", &B::Foo);
}
}
gives this error:
t.cpp: In member function 'void D::Bar()':
Line 3: error: 'void B::Foo()' is protected
- Why can I call a protected method but not take its address?
- Is there a way to mark something fully accessible from derived classes rather than only accessible from derived classes and in relation to said derived class?
BTW: This looks related but what I'm looking for a reference to where this is called out in the spec or the like (and hopefully that will lead to how to get things to work the way I was expecting).
You can take the address through
D
by writing&D::Foo
, instead of&B::Foo
.See this compiles fine : http://www.ideone.com/22bM4
But this doesn't compile (your code) : http://www.ideone.com/OpxUy
Why can I call a protected method but not take its address?
You cannot take its address by writing
&B::Foo
becauseFoo
is a protected member, you cannot access it from outsideB
, not even its address. But writing&D::Foo
, you can, becauseFoo
becomes a member ofD
through inheritance, and you can get its address, no matter whether its private, protected or public.&B::Foo
has same restriction asb.Foo()
andpB->Foo()
has, in the following code:See error at ideone : http://www.ideone.com/P26JT
This is because an object of a derived class can only access protected members of a base class if it's the same object. Allowing you to take the pointer of a protected member function would make it impossible to maintain this restriction, as function pointers do not carry any of this information with them.
Yes, with the passkey idiom. :)
Since only
derived
has access to the contructor ofderived_key
, only that class can call thefoo
method, even though it's public.The obvious problem with that approach is the fact, that you need to friend every possible derived class, which is pretty error prone. Another possible (and imho better way in your case) is to friend the base class and expose a protected
get_key
method.See the full example on Ideone.
I believe
protected
doesn't work the way you think it does in C++. In C++protected
only allows access to parent members of its own instance NOT arbitrary instances of the parent class. As noted in other answers, taking the address of a parent function would violate this.If you want access to arbitrary instances of a parent, you could have the parent class friend the child, or make the parent method
public
. There's no way to change the meaning ofprotected
to do what you want it to do within a C++ program.But what are you really trying to do here? Maybe we can solve that problem for you.
This question has an error. You cannot do a call either
As another answer says if you access the non-static protected member by a
D
, then you can. Maybe you want to read this?As a summary, read this issue report.