1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

New style headers versus Old style headers

Discussion in 'C' started by goodredhat, Mar 18, 2006.

  1. goodredhat

    goodredhat New Member

    Joined:
    Mar 18, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    Can anyone please tell me why including a new-style header might give completely different results as compared to including the old-style header in the following fairly trivial case ? Using VC++ 6, I write :
    Code:
    #include <fstream.h>
    
    class CMyLog : public ofstream
    {
    public :
    
    	CMyLog& operator<<(const char * ptr)
    	{
    		ofstream::operator<<(ptr);
    		return *this;
    	}
    
    };
    
    int main()
    {
    	CMyLog mylog;
    	mylog.open("c:\\mylog");
    	mylog << "hello world";
    	return 0;
    }
    
    The mylog file contains the string "hello world". Now just change the first line to use new-style headers, i.e. put in the following

    #include <fstream>
    using namespace std;

    Now the mylog file contains the numeric value of a pointer !

    Can anyone please tell me what is going on ? I need urgent help.

    Thank you
    Manish Jain
     
    Last edited by a moderator: Mar 19, 2006
  2. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    734
    Likes Received:
    37
    Trophy Points:
    0
    Hey it will be interesting to know. I could not get any hint after debugging.
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
    Hey its simple. Just When you are calling the base class implementation with
    ofstream::eek:perator<<(ptr);
    Actually you are calling the address of the actual string but the old implementation requires no type casting and so it prints the string but the new one prints the address of the ptr into the file.
     
  4. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    734
    Likes Received:
    37
    Trophy Points:
    0
    Yeah that could be the only reason.
     
  5. goodredhat

    goodredhat New Member

    Joined:
    Mar 18, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    ok, so what be the easiest way to get the new-style header to actually the print the string rather than the address ? Merely casting, you might notice, has no effect here.
     
  6. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
    Yeah I noticed that. Probably you need to be doing it in a bit different way
    Code:
    friend ostream & operator << (ostream &out,const char * ptr)
    {
    	out<<ptr;
    	return out;
    }
     

Share This Page