How to correctly overload the << operator with seperate bodies for fstream and ostream ?
I am trying to overload the << operator for files and cout in a Complex Number Class... friend ostream& operator<<(ostream& os, const Complex& c) { std::ofstream* p_ofs = dynamic_cast<std::ofstream*>(&os); if( p_ofs == NULL ) { os.precision(6); os.setf(ios::fixed); os<<"("<<c.real<<","<<c.imag<<")"; } else { p_ofs->setf(ios::fixed); (*p_ofs)<<c.real<<" "<<c.imag; } return os; } Now, on calling cout<<Complex(2,2)<<endl; , I get (2,2) just as I wanted... But, on calling file<<Complex(2,2)<<endl; , I get (2,2) in the file, in which I wanted 2 2 ... Why is there a similarity of outputs? //I tried overloading this function for fstream, but that failed. So, I tried dynamic cast...