Re: making overridden methods "more private"
On Oct 13, 4:19 am, 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. 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?
This behavior is correct and the practice of doing so is quite
common e.g:
I would want clientA have access to my, but no other. Therefore
derive from an interface defined by clientA, making all
implemented member functions private. It then becomes
obvious that only clientA is to call this. Also, if you
require multiple levels of access, this helps to highlight
responsibility and design intent. Obviously it can always
be circumvented, but in that case it clearly ignores
intent. e.g.
struct Interface1 //For client1
{
virtual void do1() = 0;
//May be delete through this interface
virtual ~Interface1(){ }
};
struct Interface2 : Interface1 //For client2
{
//Additional interface for c2
virtual void do2() = 0;
protected:
~Interface2(){ } //c2 won't delete, c1 may
private:
virtual void do1() = 0;//using Interface1::do1 would do.
};
struct Impl : Interface2
{
//...
private:
virtual void do1();
virtual void do2();
//And perhaps destructor too...
};
Now looking from the client's perspective it is more
sensible, e.g:
void Client2::foo( Interface2& service )
{
service.do2(); //Works fine!
service.do1(); //Fails to compile!
delete &service; //Fails to compile.
//If you cast service, you're on your own, because
// then you lied concerning the argument.
}
Why do you feel blindsided? This behavior is necessary.
Kind regards,
Werner
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]