More C++ Idioms/Virtual Friend Function

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Contents

[edit] Intent

[edit] Also Known As

[edit] Motivation

Friend function can not be made virtual because making a function friend of the base class does not make that function as friend of the derived class. Thus friend relationship can not be inherited. However, the desired effect can be obtained using so called "Virtual Friend Function" idiom. Please see the references.

[edit] Solution and Sample Code

    class Base {
    public:
      friend ostream& operator<< (ostream& o, const Base& b);
      // ...
    protected:
      virtual void print(ostream& o) const;
    };
 
    inline ostream& operator<< (ostream& o, const Base& b)
    {
      b.print(o);
      return o;
    }
 
    class Derived : public Base {
    protected:
      virtual void print(ostream& o) const;
    };

[edit] Known Uses

[edit] Related Idioms

[edit] References

http://www.parashift.com/c++-faq-lite/friends.html#faq-14.3 http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.11 http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Virtual_Friend_Function#Solution_and_Sample_Code