Re: Overriding methods with lower permission
On Jul 28, 7:53 pm, dani...@mail.ru wrote:
I have the following code:
class Base {
public:
virtual void f() {cout << "Base::f()" << endl;}
virtual void f(int) {cout << "Base::f(int)" << endl;}
};
class Derived : public Base {
void f() {cout << "Derived::f()" << endl;}
};
int main() {
Base *ptr = new Derived();
ptr->f();
ptr->f(1);
return 0;
}
As you can see, I overridden Base::f() from public, to private
access permission. Being the Java guy that I am, I expected a
compiler error.
Are you sure? I always thought that in Java, private meant
private; that since Derived::f() was private, it had nothing to
do with Base::f() (except, of course, that its presence would
prevent you from overriding Base::f()). (But I'm far from
sure.)
But to my surprise, the program ran fine, and called the
private version? Is this a compiler bug (I use g++), or is the
function explicitly converted to public?
Not exactly. You're calling Base::f(), which is public. It's
not considered relevant to access control that the function
which actually gets executed is Derived::f(). (It can't be
since access control is fully resolved at compile time, and the
compiler can't know which function will actually get executed.)
In other words, access control is always applied to the static
type.
In general, it's probably not a good idea to tighten access
controls in the derived class, because it's confusing; client
code can still call the function through an interface to the
base. On the other hand, in certain rare cases, the opposite
might be appropriate: overriding a private virtual function with
a public function in the derived class.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34