Everywhere in theory, it is written that "A virtual function can be declared as a friend of another class", but practically on implementing it, the compiler throws an error saying "virtual functions cannot be friends".
Here is a C++ program to illustrate this:
#include <iostream>
using namespace std;
class extra;
class base {
public:
virtual friend void print(extra e);
void show()
{
cout << "show base class" << endl;
}
};
class derived : public base {
public:
void print()
{
cout << "print derived class" << endl;
}
void show()
{
cout << "show derived class" << endl;
}
};
class extra
{
int k;
public:
extra()
{
k=1;
}
friend void print(extra e);
};
void print(extra e)
{
cout<<"virtual friend function "<<e.k;
}
int main()
{
base* bptr;
extra e;
derived d;
bptr = &d;
// virtual function, binded at runtime
bptr->print(e);
// Non-virtual function, binded at compile time
bptr->show();
print(e);
}
Output screen: