As you might know, when we develop a simple program that runs in the system console, using the standard library iostream, we might want to have special ways of displaying a class object.

You have probably heard of the istream and ostream operators (<< and >>),  we can use overloading to change their behaviour.

Since they are not functions from our class, we must use a special keyword, friend. A friend function is neither public or private, our class doesn't control it's scope. They are classes that don't belong to a class, but have access to its private members.

Let's create a simple class to demonstrate this:

  1.  
  2. class simple{
  3. int a,b;
  4. public:
  5. friend ostream & operator < <(ostream & o, simple & s){
  6. o << s.a << " " << s.b;
  7. return o;
  8. }
  9. friend istream & operator >>(istream & i, simple & s){
  10. i >> s.a >> s.b;
  11. return i;
  12. }
  13. };
  14.  

This class has two private members, a and b. I haven't created any constructors as we don't really need them for the example. We will change the values of a and b using the input operator >> and we will display them using the output operator <<

How the istream and ostream operators work is quite simple actually. Declaring them friend gives them direct access to private members a and b. But since they don't belong to the class we must pass them a reference to the object from the class simple we want to modify: simple & s. The other parameter is the reference to the i/o stream itself, all our modifications will be "stored" in that reference and then returned.

Let me show you a basic main to show it in use:

  1.  
  2. main(){
  3. simple obj;
  4. cin >> obj;
  5. cout < < "\nDisplay my simple object: ";
  6. cout << obj << endl;
  7. system("pause");
  8. return 0;
  9. }
  10.  

In this sample main we instantiate simple in the object obj, and we then call the input operator >> to give a and b some values.

After that we display the values using the output operator <<.

This simple program generates the following output (Imagine I enter 2 and 3 as input):

2
3
Display my simple object: 2 3

If you want the full working code:

  1.  
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. class simple{
  6. int a,b;
  7. public:
  8. friend ostream & operator < <(ostream & o, simple & s){
  9. o << s.a << " " << s.b;
  10. return o;
  11. }
  12. friend istream & operator >>(istream & i, simple & s){
  13. i >> s.a >> s.b;
  14. return i;
  15. }
  16. };
  17.  
  18. main(){
  19. simple obj;
  20. cin >> obj;
  21. cout < < "\nDisplay my simple object: ";
  22. cout << obj << endl;
  23. system("pause");
  24. return 0;
  25. }
  26.  

Well I hope you enjoyed this and understood it correctly ;)

If you have any problems or suggestions feel free to comment below,
Alex