Re: Is there any reason for private virtual functions?
I was browsing the C++ FAQ Lite the other day when I came accross
The question was "When should someone use private virtuals?", and the
author answered with "almost never, but there are reasons".
Hmm, I have read documents that rather say something like "almost always,
but there are reasons not to".
So, I am asking, what are the reasons. It seems illogical to have one;
the point of a virtual function is to be overriden in a derived class, and
the derived class cannot touch anything that is private in the base
It can't call it, but it can still override it. It seems to be a common
misconception that to override a function, it must be accessible.
Has anyone ever used a private virtual function before?
Yes. The basic idea is that the base class can check pre- and postconditions
and do other stuff that must always be done when the function is called. To
ensure that the virtual funtion is always called through the wrapper and
not directly, you make it private.
So you do something like:
void foo(int i)
if (i > 1234)
throw std::range_error("greater than 1234");
virtual void do_foo(int i) = 0;
class Derived : public Base
virtual void do_foo(int i)
// i is never > 1234 here