Re: why private virtual function?
* Bo Persson, in [microsoft.public.vc.language]:
David Wilkinson wrote:
Alex Blekhman wrote:
"George" wrote:
Why do we need to fine a virtual function as private? As special
functions
we can achieve and any special limitaitons?
"[23.4] When should someone use private virtuals?"
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.4
Alex:
Don't some recommend that all virtual functions should be private,
with public non-virtual functions that provide pre- and
post-conditions?
Yes. I think the FAQ author is among those that are confused. Hardly a
reason to avoid using a feature.
No, he's not confused, but simply holds a minority position on this matter. If
I were to guess, I'd guess it's because of Marshall's strong background in other
languages. The languages you are familiar with tend to shape how you think.
The general consensus is that the C++ way of keeping accessibility ortohogonal
to all other aspects, is of practical value for pure C++ programming. I'm not
sure I (completely) share that view. E.g., it does not seem to be of positive
practical value that a private member can influence name lookup in derived
classes, that the total inaccessibility -- except for C-style casts -- does not
mean it can be ignored as an implementation detail of the base class, that
derived classes can't simply politely ignore the private parts of base classes.
Example:
<code>
class Base
{
private:
void foo() {}
public:
void bar() {}
};
struct Mixin { void foo() {} };
class Derived: public Base, public Mixin
{
public:
void bar() { foo(); } // Uh oh.
};
int main()
{
Derived().bar();
}
</code>
In each specific case there are simple workarounds, e.g. here a
'using'-declaration or qualification, but IMHO there's something not quite right
about the scheme. In short, C++ 'private' is at a much lower level of
abstraction than one naturally expects from experience with other languages. So
it's not necessarily wrong to make it a rule to avoid the uses that most
directly clash with such expectations -- although I think, if one does use
C++, then one should carefully separate issues at the technical language level
from issues about how to use the language to implement high level abstractions.
Cheers,
- Alf
CC: Marshall Cline as FAQ maintainer.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?