Re: Visibility of Protected Functions
Michael K. O'Neill wrote:
Given this code:
class A
{
private:
void Priv() {};
protected:
void Pro() {};
};
class B : public A
{
public:
void Understanding( A *otherA, B *otherB )
{
Priv();
otherA->Priv();
otherB->Priv();
Pro();
otherA->Pro();
otherB->Pro();
}
};
Then in B::Understanding(), I understand that in the first three
calls to Priv(), the function A::Priv() is inaccessible and will
be flagged as errors by the compiler.
In the calls to Pro(), I understand that the call to this->Pro()
is absolutely fine. I also understand that in otherA->Pro(),
A::Pro is not accessible through a "A" pointer or object.
But why is the call to otherB->Pro() OK? And what is the
rationale for it being OK (e.g., where is it useful)?
Every object of class B can access B's private and protected members
of any other object of class B.
This allows you to write:
class X
{
private: // or protected, doesn't matter
int i;
public:
X(int v = 33) : i(v) {}
X(const X& o) : i(o.i) {} // we can copy i although it is private
void dummy() { std::cout << i; }
};
Back to your example, A::Pro is visible to B objects because of the
inheritance. So each and every B object can access any other's
B::Pro member (even though it happens to be defined in A), simply
because it can access it's own B::Pro member.
IOW, private/protected "boundaries" are not enforced at object
(instance) level (how could they?), but at class level.
--
IR
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]