overloading insertion operator

just a question I've been reading tutorials and no one actually explains why you need to use an ostream object when overloading the << operator why can't I just use my object to overload the << operator

for example
1
2
3
4
5
6
7
8

ex& operator<<(ex& out,ex& e){


   // code
}



instead of this VV

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>

using namespace std;

class ex{

public:

    int age;
    int weight;
    friend ostream& operator<<(ostream& out,const ex& e);



};


ostream& operator<<(ostream& out,const ex& e){


   return out << e.age << "  " << e.weight;

}

int main()
{

   ex one;
   one.age = 19;
   one.weight = 203;
   cout << one;

}



Last edited on
> why you need to use an ostream object when overloading the << operator
> cout << one;
¿what is `cout'?
cout belongs to the c++ standard library as far as I know?
closed account (E0p9LyTq)
9.3 — Overloading the I/O operators « Learn C++
http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/
thanks furryguy I have a hell of a lot of study to do tonight =O =)
closed account (E0p9LyTq)
I'll make another suggestion, get rid of using namespace std;, use std::cout instead.

1.3a — A first look at cout, cin, endl, the std namespace, and using statements
http://www.learncpp.com/cpp-tutorial/1-3a-a-first-look-at-cout-cin-endl-namespaces-and-using-statements/

using namespace std; is not wrong, but just bad practice. Especially when used at global scope.

Why is " using namespace std " in C++ considered bad practice - Stack Overflow
http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice
Last edited on
thanks FurryGuy yeah I seen in other threads people mention it's better practice to use std::cout etc instead of using namespace std I'll look into it =)
closed account (E0p9LyTq)
When I first started out learning C++ I used using namespace std;. After having more than a few people suggest using it could cause problems I stopped using it.

Now I can't type just cout, my fingers automatically add the std:: even if I am modifying code that has the using directive (using namespace std;).
what types of things can go wrong with using namespace std
closed account (E0p9LyTq)
Read the Stack Overflow link I gave you, it give examples of what could go wrong.
You can have name clashes. For example say you're doing something simple, like converting a vector<char> to upper case.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cctype>
#include <vector>
#include <algorithm>

using namespace std;
int main()
{
    std::vector<char> answers{'a','b','c','d'};
    std::transform(answers.begin(), answers.end(), answers.begin(), toupper);

}


Edit: With the using statement this will fail to compile. Without this statement the program will compile.

Last edited on
Topic archived. No new replies allowed.