Re: making overridden methods "more private"
On 13 Okt., 04:19, Jeffrey Schwab <j...@schwabcenter.com> wrote:
It was always my understanding that a derived class could not make the
public members of a public base class private or protected.
This was a misunderstanding ;-)
To my surprise, g++ and Comeau both allow it. Client code can
access the member through a pointer-to-base, but not through a
pointer-to- derived. This doesn't even generate a warning in
either of the mentioned compilers. Am I missing something?
Why do I feel blind-sided?
#include <iostream>
class B
{
public:
virtual ~B() { }
virtual void method() { std::cout << "B\n"; }
};
class D: public B
{
protected:
virtual void method() { std::cout << "D\n"; }
};
int
main()
{
D d;
B& b = d;
/* error: 'virtual void D::method()' is protected */
// d.method();
/* OK, finds D::method. */
b.method();
return 0;
}
This behaviour is by design, see [class.access.virt]/1 :
"The access rules (clause 11) for a virtual function are determined
by
its declaration and are not affected by the rules for a function that
later overrides it. [ Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f()
{
D d;
B* pb = &d;
D* pd = &d;
pb->f(); // OK: B::f() is public,
// D::f() is invoked
pd->f(); // error: D::f() is private
}
-end example ][..]"
I see no harm in these rules. You would probably
apply this technique, if a derived class has a
more appropriate access to the same functionality
and you want to guide users of the derived class
to use the newer function instead.
As a side-note, C# has invented a mechanism named
"explicit interface implementation" just to realize
the same use-case and acts as a counter-part to
otherwise always public interface functions.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]