Re: Restricting access should be illegal?
Ulrich Eckhardt wrote:
johnchx2@yahoo.com wrote:
Walter Bright wrote:
Shouldn't restricting access to an overriding virtual
function be an error? After all, we can get at it anyway
via an implicit conversion. Does anyone know of a
legitimate design pattern that does this?
One possibility:
struct A { virtual int foo() { return 0; } };
class B: private A {
private:
int foo() { return 1; }
public:
// other functions use foo()
};
Basically, we want to override a public function of a
private base class.
Hmmm, for a base-class, two access-specifiers are effective,
one being the one for the baseclass itself and one being the
one for the particular element thereof. The result of these
two stages is always the most restrictive access-specifier.
That's true for the members of A. B::foo() isn't a member of A;
it's a member of B. The question was why allow B::foo() to be
private when A::foo() is public.
This means two things:
1. Your example is bad because access to A::foo() is already private
because access to A is private.
A::foo() isn't private to anyone who has an A*. And of course,
however calls A::foo() actually ends up in B::foo(). The
reasoning was that it makes no sense to make B::foo() private,
because anyone with a B* can access it as public by converting
the B* to an A*. The counter-example is, of course, when the
inheritance is private: someone with a B* here cannot get the A*
necessary to access it, so the function is private to such
users.
2. Your example is good because it shows a typical and common
case where the access to the baseclass' members via the
derived class is different from the direct access.
That said, changing access in a way that is not enforced by
the compiler and which might even give people a false feeling
of security is a nono. I'd call it worth a warning by a good
compiler. OTOH, others even presented this as idiomatic, so I
don't think that will happen.
I think the case probably most often occurs when A is some sort
of callback interface. Some member function of B registers the
object for the callback. (A member fucntion of B can convert
the B* this pointer to an A*.) No other user ever sees an A*.
Nor can it: because derivation is private, the conversion B* to
A* is illegal.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]