Solved

cout/cin overload

Posted on 2001-08-08
8
1,975 Views
Last Modified: 2010-08-05
Is it possible to overload cout & cin ?
if so, how? if not, why ?
0
Comment
Question by:ls1429
8 Comments
 
LVL 4

Expert Comment

by:IainHere
Comment Utility
Yes, they're overloadable - that's pretty much the reason they were developed.  Don't forget that cout is defined as

extern ostream cout;

say you have your own class:

class WriteMe{
public:
    double m_writethis;
};

you would overload the << operator to work with cout like this:

ostream& operator<< (ostream&s, const WriteMe& write)
{
   return s << "your formatting here " << write.m_writethis;
}

[Ignoring the publicness of the member variable and the uselessness of the class]
0
 
LVL 4

Expert Comment

by:IainHere
Comment Utility
Oh, and the cin being istream can be overloaded in the same fashion (of course, the class you're overloading for cannot be const in this case, and you must remove any formatting you define in the ostream - I've ignored this removal because it would complicate matters, and I'd probably get it wrong anyway :)

istream& operator>> (istream& s, WriteMe& write)
{
   s >> write.m_writethis;
   return s;
}

Of course in a real case, you'd have to put all sorts of error checking in there too.

you would use this exactly as you would a built in type:

WriteMe   bob;
bob.m_writethis = 77;
cout << bob;

...

WriteMe   bill;
cin >> bill;  //ignoring the formatting again.
0
 

Author Comment

by:ls1429
Comment Utility
The above code ( tested for cout )did not got compiled.
But when I changed the overload function to friend function it got magically compiled.
I dont know why I got problems and by friend function how it solved/ redirected the purpose.

Can you explain ?
0
 
LVL 1

Expert Comment

by:glebspy
Comment Utility
I just wanted to make a technical point.

cin and cout are objects. It's not possible to overload them, and the phrase doesn't even mean anything. It's only possible to overload functions (of which operators like << are a special case).

when you employ Iainhere's solution (he correctly guessed what you meant), you are using a different(overloaded) operator<<, but the same cin and cout.

It's possible to over*ride* cin and cout by saying something silly like

float cin;

or

string cout;

after which operator<< doesn't work any more..
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 4

Expert Comment

by:IainHere
Comment Utility
>>But when I changed the overload function to friend function it got magically compiled.

Could you post the code - I don't understand.  In the meantime, here's the code for a functioning example (I just tested it).

#include <iostream>
using namespace std;

class WriteMe{
public:
   double m_writethis;
};

ostream& operator<< (ostream&s, const WriteMe& write)
{
  return s << "your formatting here " << write.m_writethis;
}

int main(int, char**)

{
     WriteMe jeff;
     jeff.m_writethis = 33;
     cout << jeff;    
     return 0;
}
0
 
LVL 1

Accepted Solution

by:
glebspy earned 25 total points
Comment Utility
>The above code ( tested for cout )did not got compiled.
>But when I changed the overload function to friend function it got magically compiled.
>I dont know why I got problems and by friend function how it solved/ redirected the purpose.

>Can you explain ?


I've  encountered exactly this situation many times, and the right thing to do is to make the overloaded operator a friend function.

The reason is that the overloaded >> and << are not members of Iainhere's class Writeme! They are global. You can't make them member functions of Writeme. Imagine you had

class Writeme{
 double m_writethis;
 ostream&operator<<(ostream&a){return a<<m_writethis}
}bill;
that would work but you'd have to say
bill<<cout;
rather than cout<<bill; which is what I'd consider desirable.

So if you try to access

istream& operator>> (istream& s, WriteMe& write)
           {
             s >> write.m_writethis;
             return s;
           }

*operator>> has to have access to the member m_writethis*
so either m_writethis has to be declared public: (remember
members of a class are private by default) or the global operator>> has to be declared a friend. I personally use the friend way of doing things since I might want to write out all sorts of members of the class in the cout<< call, some of which I might think were more private than others.

I usually call writing functions which only have access to public members `display' or `show' rather than using operator<<, and then these are not friends and so they can only write out the public members.
0
 
LVL 11

Expert Comment

by:griessh
Comment Utility
I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. Unless there is objection or further activity,  I will suggest to accept "glebspy, IanHere" comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points.
The link to the Community Support area is: http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0
 
LVL 5

Expert Comment

by:Netminder
Comment Utility
Per recommendation comment force/accepted by

Netminder
Community Support Moderator
Experts Exchange

IainHere: points for you at http://experts-exchange.com/jsp/qShow.jsp?ta=cplusprog&qid=20278011
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now