"Kevin Saff" <> wrote...
> Apparently I'm missing something. Stroustrup (15.3) says of protected
> access:
>
> If [a member] is protected, its name can be used only by member functions
> and friends of the class in which it is declared and by member functions
and
> friends of classes derived from this class.
>
> Since private access cares about the calling class rather than the calling
> object, I assumed the same was true for protected access, but the
following
> code fails in MSVC6:
>
> class B
> {
> protected:
> virtual void speak() {
> std::cout << "Howdy, I'm B" << std::endl;
> }
> };
>
> class D : public B
> {
> public:
> void listen(B& other) {
> std::cout << "It says: ";
> other.speak();
> }
> };
No, you can only access 'speak' in the same object as '*this'.
You cannot access 'speak' in another object because it may not
be your subobject. Imagine
class DD : public A, public B { ...whatever... };
D d;
DD dd;
d.listen(dd);
what would happen? You'd try to access a part of object from
a different hierarchy.
>
> // error C2248: 'speak' : cannot access protected member declared in class
> 'B'
>
> Is this correct?
Yes.
> So, protected access is granted only to the derived
> object, rather than the derived class?
Yes.
> Can I do something like this without
> relying on public access?
Describe the problem you're trying to solve.
Victor
|