Virtual Friend Function

Discussion in 'C++' started by Mridula, Mar 2, 2009.

  1. Mridula

    Mridula New Member

    Joined:
    Mar 5, 2008
    Messages:
    316
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    S/w proffessional
    Location:
    Bangalore

    Introduction



    This talks about Virtual Friend Function in C++.

    Background



    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:
    
    #include<iostream.h>
    
    class Base {
        public:
          friend ostream& operator<< (ostream& o, const Base& b);
          // ...
        protected:
          virtual void print(ostream& o) const{cout<<"Base\n";};
    };
    
    inline ostream& operator<< (ostream& o, const Base& b)
    {
        b.print(o);
        return o;
    }
    
    class Derived : public Base {
          protected:
          virtual void print(ostream& o) const{cout<<"Derived\n";};
    };
    
    int main()
    {
    Derived d;
    
    cout<<"My current object is:"<<d<<"\n";
    
    return (0);
    }
    
    Output:
    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)."
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Article of the month competition nomination started here
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice