Tutorial :ABC Virtual OStream Insertion Operator



Question:

Consider the following snippet:

struct ObjectInterface  {      virtual ~ObjectInterface() {}      virtual void Print(std::ostream& target) const = 0;  };    struct Foo : ObjectInterface  {      virtual void Print(std::ostream& target) const      {          target << "Foo";      }  };    struct Bar : ObjectInterface  {      virtual void Print(std::ostream& target) const      {          target << "Bar";      }  };  

Is there any way to change Print in ObjectInterface to the standard "std::ostream& operator<<"-type of output? I can't make it work.

EDIT: I'm basically trying to figure out if I can make friend work with virtual.


Solution:1

You need a free function:

ostream & operator << ( ostream & os, const ObjectInterface & oi ) {      oi.Print( os );      return os;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »