Re: Restricting access should be illegal?
Walter Bright wrote:
Consider the following legal code:
-----------------------
#include <stdio.h>
class A {
public:
virtual void Member() { printf("A::Member\n"); }
};
class B : public A {
private:
virtual void Member() { printf("B::Member\n"); }
};
int main()
{
B *b = new B();
// b->Member(); // error, B::Member is private
A *a = b;
a->Member(); // calls B::Member
}
-------------------------
Shouldn't restricting access to an overriding virtual function be an
error?
No, because there is a difference between invoking a method and
executing a method. Access levels can prohibit the invocation of a
class method outside of certain program contexts - but they have
nothing to do with prohibiting a method's execution at all. Nor would
prohibiting a method's execution really make much sense as a concept -
since every method has to be able to execute at some point (otherwise,
why would the method exist in the first place?). So what would it mean
to prohibit a method's execution only some of the time? How could that
notion be formalized and why would it be useful?
In reality, a class method cannot safely make any assumptions about its
caller - it can only make assumptions about the state of its class
object at the point it begins its execution. In other words, a class
method can count on its necessary preconditions having been met before
it is called, the called method just cannot assume that some other
particular function was the one that called it (though often that
information can be deduced if only one other routine can fulfill its
necessary preconditions).
The example program above shows nothing more than this method
invocation vs. execution distinction. The program contrives to execute
B::Member but does not do so by invoking B::Member itself. And while it
may not make much sense to use access levels in this manner, there is
no reason to make this use illegal - since nothing about the program
should be surprising.
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]