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:
When you write
virtual friend void print(extra e);
C++ interprets this to mean “there is a free function named print
, which isn't a member function of the current class, and it's virtual.” That combination can't happen, since virtual functions must be member functions of a class.
What you can do is take an existing virtual function defined in another class and make it a friend of the class. So, for example, if there's a virtual function OtherClass::myFn
, you could write
friend void OtherClass::myFn();
to say “that particular virtual function is a friend of me.” As a note, though, this just makes OtherClass::myFn
a friend of the class; any overrides of OtherClass::myFn
won't be friends of the class, since friendship isn't be inherited.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.