Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 810
Javier J. Salmeron Garcia Avatar asked Sep 09 '26 02:09

Javier J. Salmeron Garcia


1 Answers

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!
}
like image 127
Nawaz Avatar answered Sep 10 '26 15:09

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!