CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Threaded View

  1. #1
    Join Date
    Apr 2008
    Posts
    12

    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.


    Code:
    #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
    }
    Last edited by darlingm; May 8th, 2012 at 06:24 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured