Inherit from cout - how to override "<<" operator & forward to base

Using c++11, but I don't think that matters here.

output.displayHeader() must execute before the inherited from ostream (cout) executes streaming data, or bad things happen. It's of course not as simple as in the example below, and I need to make sure displayHeader() is never missed.

I'm thinking I need to override the "<<" operator, having my own function call displayHeader(), then call the base (cout) "<<" operator. What's the proper syntax for doing this?

I can't call displayHeader() in the constructor, and I can't call it right after the object is defined. There are exception case scenarios where displayHeader() must not be called, and other things must happen instead.

I'm aware this will result in many redundant bool comparisons versus the way I'm doing it now, and I'm perfectly OK with that.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

class myOutput : public ostream {
   public:
      myOutput() : ostream(cout.rdbuf()) {
      }
      void displayHeader() {
         if(false == displayedHeader) {
            *this << "HEADER" << endl;
            displayedHeader = true;
         }
      }
   private:
      bool displayedHeader { false };
};

int main() {
   myOutput output;
   output.displayHeader();  // <-- I want this line to go away
   output << "Hello" << endl;   // <-- By having this line call displayHeader()
   output << "Hello, again" << endl;   // <-- and likewise this one, but it will see displayedHeader is true
}
Topic archived. No new replies allowed.