Search code examples
c++inheritanceoperatorsfriend

Operator << and inheritance


I have the following classes in C++:

class Event {
        //...
        friend ofstream& operator<<(ofstream& ofs, Event& e);

};


class SSHDFailureEvent: public Event {
    //...
    friend ofstream& operator<<(ofstream& ofs, SSHDFailureEvent& e);
};

The code I want to execute is:

main() {

 Event *e = new SSHDFailureEvent();
 ofstream ofs("file");
 ofs << *e; 

}

This is a simplification, but what I want to do is write into a file several type of Events in a file. However, instead of using the operator << of SSHDFailureEvent, it uses the operator << of Event. Is there any way to avoid this behavior?

Thanks


Solution

  • That would not work, as that would call operator<< for the base class.

    You can define a virtual function print in base class and re-define it all derived class, and define operator<< only once as,

    class Event {
    
          virtual ofstream& print(ofstream & ofs) = 0 ; //pure virtual  
    
          friend ofstream& operator<<(ofstream& ofs, Event& e);
    };
    
    //define only once - no definition for derived classes!
    ofstream& operator<<(ofstream& ofs, Event& e)
    {
       return e.print(ofs); //call the virtual function whose job is printing!
    }