This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Access to protected members from derived class via pointer


On Mon, Jul 05, 1999 at 01:22:23PM -0300, Alexandre Oliva wrote:
> On Jul  5, 1999, Klaas Teschauer <klaas@kite.rhein-main.de> wrote:
> 
> > The compiler flags a statement, that uses a pointer to accesses a
> > protected member of the base class within the derived class as
> > invalid. However, a direct access (not using a pointer) is accepted.
> 
> That's right.  A derived class can only access a protected member of a
> base class using a pointer or reference to the derived class,
> otherwise one could violate type safety by messing up sub-objects of
> other derived classes.  Yes, this is different from Java.

AFAIK Java does not know the concept of a "pointer" at all, so I fail to
understand how this could possibly apply to Java.

Returning to the problem, I still maintain that this is a bug. Here's
why:

Based on my knowledge of C++, the keywords "public", "protected" and
"private" are exclusively relevant for access control. They enable the
compiler to decide wether a statement referencing a class member is
allowed or not.

Secondly, in C (and therefore C++), accessing a variable (or struct member)
using a pointer or the variable name is purely a matter of choice and yields
always the same results (all other things being equal):

	printf( "%d", s.member );

gives exactly the same result as:

	printf( "%d", p->member );

if p == &s is true.
	
>From my perspective, this unavoidably means for C++, that if

	o.member

is allowed by the applicable access control,

	o->member

must also be allowed.

Put it another way, if we revisit the sample program I provided in the bug
report and modify it slightly, making Base::member public, egcs accepts
the accesses to Base::member even using a pointer:

class Base
{
public:
  int member;

protected:
  int memfunc( Base *p ) const;
};

int Base::memfunc( Base *p ) const { p->member; }

class Subclass : public Base
{
public:
  int testfunc( Base *o ) const;
};


int Subclass::testfunc( Base *o ) const
{
  int i = member;
  memfunc( o );

  i = o->member;  // (mysteriously) accepted because `member' is public
  o->memfunc( o );  // memfunc is protected, no accepted

  return i;
}

With this in mind, I fail to see how this on principle would violate
type safety. If your argument would be true, then we cannot allow
access to class members via a pointer (or reference) _at all_.

	Klaas Teschauer


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]