Listing 2: The NetObject class

class NetObject
{
protected:

  virtual void netWrite (NetBuffer& nbuf) const = 0;
  virtual void netRead  (NetBuffer& nbuf) = 0;


  void netCopy (const NetObject& obj)
  {
    NetObject nobj( obj.toBuffer() );
    netRead ( nobj );
  }

  void netClear()
  {
    NetBuffer nbuf;  // empty
    netRead(nbuf);   // fill with 0
  }

public:

  NetObject () {}
  virtual ~NetObject() {}

  size_t netSize() const
  {
    NetBuffer nbuf;  // empty
    netWrite(nbuf);  // attempt to write
    return nbuf.bytesWritten();
  }

  Buffer toBuffer() const
  {
    NetBuffer nbuf( netSize() ); // allocate enough space
    netWrite (nbuf);
    return nbuf.buffer();
  }

  friend inline NetBuffer&
  operator >> (NetBuffer& nbuf, NetObject& obj)
  {
    obj.netRead( nbuf );
    return nbuf;
  }

  friend inline NetBuffer&
  operator << (NetBuffer& nbuf, const NetObject& obj)
  {
    obj.netWrite( nbuf );
    return nbuf;
  }
};

bool operator==(const NetObject& obj1, const NetObject& obj2)
{
  if (&obj1 == &obj2) return true;
  return (obj1.toBuffer() == obj2.toBuffer() );
}

bool operator!=(const NetObject& obj1, const NetObject& obj2) 
{
  return !(obj1 == obj2);
}
— End of Listing —