Private virtual function

//Can virtual function be private?
//Suppose virtual function vf() is declared as private in base.Even though vf is overriden as public in derived compiler will throw error of private at run time. But one work around could be given to declare a virtual function as private by making main() as friend function of that class.Because friend functions can access the private members.
#include<iostream>
using namespace std;
class base
{
private:
        virtual void vf(){cout<<"base::vf"<<endl;}
//friend int main();
};
class derived:public base
{
public:
void vf(){cout<<"derved::vf;"<<endl;}
};
int main()
{
base* bp = new derived;
bp->vf();//error: ‘virtual void base::vf()’ is private

return 0;
}

No comments:

Post a Comment