C++ Abstract class operator overloading and interface enforcement question
c++
Solution
The common convention for this is to have a `friend` output operator at the base level and have it call private virtual function:
class Base
{
public:
/// don't forget this
virtual ~Base();
/// std stream interface
friend std::ostream& operator<<( std::ostream& out, const Base& b )
{
b.Print( out );
return out;
}
private:
/// derivation interface
virtual void Print( std::ostream& ) const =0;
};
Problem
(edited from original post to change "BaseMessage" to "const BaseMessage&") Hello All, I'm very new to C++, so I hope you folks can help me "see the errors of my ways". I have a hierarchy of messages, and I'm trying to use an abstract base class to enforce an interface. In particular, I want to force each derived message to provide an overloaded << operator. When I try doing this with something like this: ``` class BaseMessage { public: // some non-pure virtual function declarations // some pure virtual function declarations virtual ostream& operator<<(ostream& stream, const BaseMessage& objectArg) = 0; } ``` the compiler complains that "error: cannot declare parameter ‘objectArg’ to be of abstract type ‘BaseMessage’ I believe there are also "friend" issues involved here, but when I tried to declare it as: `virtual friend ostream& operator<<(ostream& stream, const BaseMessage objectArg) = 0;` the compiler added an addition error "error: virtual functions cannot be friends" Is there a way to ensure that all of my derived (message) classes provide an "<<" ostream operator? Thanks Much, Steve