Virtual-Friend Function Idiom

 

I just noticed this term when I was freshing up with C++ FAQ.

In the case of member functions call, it will act upon the object which is used to call the function.

To achieve dynamic binding with friend functions, we have to make the interfaces as virtual to operate within the friend function. This is what we call ‘Virtual-Friend Function Idiom’. It’s not a big deal. Just don’t surprise on hearing this term next time.

See the sample snippet.

class Base
{
public:
virtual void print() const { cout << “base”; }
friend ostream& operator << (ostream& obj, const Base& b);
};

class Derived : public Base
{
public:
void print() const { cout << “Derived”; }
};

ostream& operator<< (ostream& obj, const Base& b)
{
b.print();
return obj;
}

int main()
{
Derived d;
cout << d;
return 0;
}

 

Disclaimer

 

The information in this weblog is provided “AS IS” with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Inappropriate comments will be deleted or modified at the authors discretion. All code samples are provided “AS IS” without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose. In addition, my thoughts and opinions change from time to time. I consider this a necessary consequence of having an open mind. This weblog is intended to provide a semi-permanent point in time snapshot and manifestation of the various memes running around my brain, and as such any thoughts and opinions expressed within out-of-date posts may not the same, nor even similar, to those I may hold today.