Re: C2248: cannot access protected member
- From: "Ben Voigt [C++ MVP]" <rbv@xxxxxxxxxxxxx>
- Date: Thu, 31 Jan 2008 15:47:22 -0600
"Doug Harrison [MVP]" <dsh@xxxxxxxx> wrote in message
news:3td4q35lnijrv5top8i9m712d7ohr3r1c3@xxxxxxxxxx
On Thu, 31 Jan 2008 14:14:15 -0500, "Igor Tandetnik" <itandetnik@xxxxxxxx>
wrote:
The short answer is that the C++ standard says so:
11.5/1 When a friend or a member function of a derived class references
a protected nonstatic member of a base class, an access check applies in
addition to those described earlier in clause 11. Except when forming a
pointer to member (5.3.1), the access must be through a pointer to,
reference to, or object of the derived class itself (or any class
derived from that class) (5.2.5). If the access is to form a pointer to
member, the nested-name-specifier shall name the derived class (or any
class derived from that class).
So &X::foo fails the access check, but &Y::foo works.
Here's the long answer. Class Y is presumed to know how it uses
protected members of its base class X, and can access them freely. But
it doesn't necessarily know how some other class Z derived from X might
use X's protected members, and is not allowed to mess up with those.
Consider:
class Z : public X {};
void Y::baz(Z* pz) {
X::foo(); // fine - calls foo() on itself
pz->X::foo(); // doesn't compile - calls foo on Z
int b = X::a; // fine - access its own members
b = pz->X::a; // doesn't compile
}
If &X::foo worked inside Y, baz() could have worked around the
restrictions like this:
void Y::baz(Z* pz) {
void (X::*pf)() = &X::foo; // hypothetical, doesn't compile
(pz->*pf)(); // same as pz->foo()
}
I was thinking the same thing, but it doesn't seem like the compiler would
let you say the following even if the hypothetical initialization worked:
(pz->*pf)();
Of course it would, pf was declared as a pointer-to-member of any X
for the same reason it doesn't allow:
pz->foo();
That's why the initialization fails, because baz isn't allowed to call foo
on any X, which is part of the type for pf.
However, it would let you say:
(this->*pf)();
which is potentially useful in a limited way. Am I missing something?
--
Doug Harrison
Visual C++ MVP
.
- References:
- C2248: cannot access protected member
- From: Alex Blekhman
- Re: C2248: cannot access protected member
- From: Igor Tandetnik
- Re: C2248: cannot access protected member
- From: Doug Harrison [MVP]
- C2248: cannot access protected member
- Prev by Date: Re: time_t can not represent date before 1970-01-01 and after 2038-02-19?
- Next by Date: Re: C2248: cannot access protected member
- Previous by thread: Re: C2248: cannot access protected member
- Next by thread: Re: C2248: cannot access protected member
- Index(es):
Relevant Pages
|
Loading