You are here

Derivation of the inner class from std::streambuf

The inner class OG_constreambuf is inherited from streambuf.

class OG_constreambuf : public std::streambuf
{
public:
  OG_constreambuf(int iBuffersize=100);
  virtual ~OG_constreambuf();

private:
  void WriteCharToConsole(int);
  void WriteToConsole();
  void DeleteConsole();
  void CreateConsole();

  HANDLE hConsoleOut;
  char* pReserve;
protected:
  int_type overflow(int_type);
  int_type sync();
};

The public and protected methods override methods of the base class, the private methods extend the class. The class uses an output buffer (pReserve) which is reserved in the constructor. The constructor allows you to specify the buffer size.

OG_constreambuf::OG_constreambuf(int iBuffersize)
{
  if (iBuffersize)
  {
    pReserve = new char[iBuffersize];
    setp(pReserve, pReserve + iBuffersize);
  }
  else
  {
    pReserve = NULL;
    setp(0, 0);
  }

  setg(0, 0, 0);

  CreateConsole();
}

The constructor then calls the functions setp, setg and CreateConsole on. The functions setp and setg are derived from the base class and are used to publish the input or output buffer to the Stream class. setp sets the beginning and the end of the output buffer, setg is the counterpart for the input buffer (here 0, because no input buffer is available). The CreateConsole method opens a console window. If a console window already exists, it is first destroyed. The HANDLE hConsoleOut is needed for output.

void OG_constreambuf::CreateConsole()
{
  if (!AllocConsole())
  {
    FreeConsole();
    AllocConsole();
  }
  hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
}