Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Virtual Friend Function (http://www.go4expert.com/articles/virtual-friend-function-t16397/)

Mridula 2Mar2009 17:29

Virtual Friend Function


This talks about Virtual Friend Function in C++.


Friend functions are not in-herited in C++. So, to achieve dynamic binding with friend functions, we have to make the interfaces as virtual (make it as protected part of class) to operate within the friend function. This is what we call as Virtual-Friend Function.

The code

Here is an example to explain the above concept.

Code: Cpp


class Base {
      friend ostream& operator<< (ostream& o, const Base& b);
      // ...
      virtual void print(ostream& o) const{cout<<"Base\n";};

inline ostream& operator<< (ostream& o, const Base& b)
    return o;

class Derived : public Base {
      virtual void print(ostream& o) const{cout<<"Derived\n";};

int main()
Derived d;

cout<<"My current object is:"<<d<<"\n";

return (0);

My current object is:Derived

Here, the function "operator <<" in main (Base& b) will invoke b.print(o), which is virtual. So here in main that Derived-print(o) will get control, as "b" is actually a object of class Derived.

Note here that "Derived" class overrides the behavior of the protected: virtual member function print(o) and it does not have its own implmentation for friend function "operator << (ostream& o, const Base& b)."

shabbir 6Apr2009 15:02

Re: Virtual Friend Function
Article of the month competition nomination started here

All times are GMT +5.5. The time now is 04:12.