blangela
9/25/2008 8:37:00 PM
On Sep 25, 1:25 pm, blangela <Bob_Langel...@telus.net> wrote:
> On Sep 25, 12:55 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
>
>
>
>
>
> > blangela wrote:
> > > If I pass a base class object by reference (likely does not make a
> > > difference here that it is passed by reference) as a parameter to a
> > > derived class member function, the member function is not allowed to
> > > access the protected data members of the base object. This surprises
> > > me.
>
> > > Can someone explain why this is? I suspect there is a good reason and
> > > I am just having a slow day to not come up with it myself.
>
> > Isn't this in the FAQ? It should be.
>
> > In short, the reason is to prevent access to members of a different type
> > (across the hierarchy). If D1 and D2 derive from B, an instance of D1
> > is not allowed to access any non-public members of D2 (unless they are
> > friends, of course). When you pass a reference to B to a member
> > function of D1, the access to members of that class is blocked because
> > it *can* be a subobject of a D2 object, and not necessarily of another
> > D1. Need an example? Look in the archives, we had that topic discussed
> > several times over the past years.
>
> > V
> > --
> > Please remove capital 'A's when replying by e-mail
> > I do not respond to top-posted replies, please don't ask
>
> Even with the example you supply, what would be the harm of allowing
> access to a member ( a member that was declared in the B class in your
> example above) that we know must exist, no matter what subclass the
> object actually belongs to (D1, D2, a subclass of D2, etc.)?- Hide quoted text -
>
> - Show quoted text -
Also, I changed the member function to:
void Derived::Method4(Base & B_Param)
{
Derived * DPtr = dynamic_cast <Derived *> (&B_Param); // this cast
// creates a Derived class pointer to B_Param, if and only if,
// B_Param actually is Derived class object, otherwise the
// pointer will be set to 0
if (DPtr != 0) // if B_Param is actually a Derived class object
cout << DPtr->mDerived << endl;
else
{
Base B_obj = B_Param;
cout << B_obj.mBase << endl;
}
}
And I still have the same errors:
1>c:\documents and settings\blangela\desktop\polymorphismtest
\derived.cpp(29) : error C2248: 'Base::mBase' : cannot access
protected member declared in class 'Base'
1> c:\documents and settings\blangela\desktop\polymorphismtest
\base.h(17) : see declaration of 'Base::mBase'
1> c:\documents and settings\blangela\desktop\polymorphismtest
\base.h(7) : see declaration of 'Base'
I would have thought that B_obj can only be a Base object now (and not
some subclass of Base), that it would now be allowed?