Re: Is there any reason for private virtual functions?
"Jimmy" <unhandledex@gmail.com> wrote in message
news:1151666883.088741.44870@x69g2000cwx.googlegroups.com
I was browsing the C++ FAQ Lite the other day when I came accross
question #23.4
(http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.4).
The question was "When should someone use private virtuals?", and the
author answered with "almost never, but there are reasons". 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
class. Has anyone ever used a private virtual function before?
To override a virtual function, it is not necessary to have access to it.
Consider the following:
#include <iostream>
using namespace std;
class Base
{
public:
void Print()
{
PrintImplementation();
}
private:
virtual void PrintImplementation()
{
cout << "Base\n";
}
};
class Derived : public Base
{
private:
virtual void PrintImplementation()
{
cout << "Derived\n";
}
};
int main()
{
Base b;
Derived d;
Base * ptr0 = &b;
Base * ptr1 = &d;
ptr0->Print();
ptr1->Print();
return 0;
}
This model of public non-virtual functions and non-public virtual functions
is recommended by Sutter and Alexandrescu (C++ Coding Standards) in some
cases.
The idea is that the public non-virtual function provides an unchanging
interface, whereas the non-public virtual function provides an
implementation that can change as needed. Thus you could increase the number
of arguments of the virtual function without altering the class interface.
You can also have the public non-virtual function call multiple virtual
functions and derived classes can be selective in what they override.
--
John Carson