operator <<

Cant wait to know why 1 thing is working but the other is not

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string message = "Hello World!\n";  
    operator<<(cout, message);       // this works =]

    int x = 2;
    operator<<(cout, x);       // so amazingly interesting why this is not =/
}


Also while this is a topic want to ask about overloaded operators.

1st question

My_class operator+(const My_class & ...) const {}
In this case i understand that its like method (operator+) that will take My_class object as argument and will return another My_class object. Its like making normal method.


ostream& operator<<(ostream& os, const My_class& ....) {}
Here im loosing myself.
From examples i understand that operator<<(cout, x); is the same as cout << x;
But on what are we actually using this method operator<< (previosuly it was rasy to understand --- > My_class.operator+(const My_class & ...))

Now we are calling this method operator<< on pure air

2nd question
When exactly this cout object is being created and is it really an object?
In My_class example we have to actually create My_class object to give it as argument to operator+. Now we just insta give it as argument to operator<<(cout, x).

Explanation of this would mean a lot to me :)
Last edited on
The difference between non-members and members.
http://www.cplusplus.com/reference/string/string/operator%3C%3C/
http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

Operators are "syntactic sugar". Binary operator OP is used in code:
lhs OP rhs
If the OP is a member function of the typeof(lhs), then it just takes the rhs as parameter.
If the OP is not a member, then it takes both lhs and rhs as parameters.

The lhs of operator<< is an std::ostream. You cannot modify the code of std::ostream. Therefore, you have to write a non-member overload for your type (My_class).


The std::cout behaves like a global variable that is defined somewhere within the standard library.
Thanks for good info of course but was looking that it but still didnt understand how could i type

1
2
int x = 2;
    operator<<(cout, x);

in a way that it actually works
Than i could understand better how this works

ostream& operator<< (ostream& os, const string& str);

Looking at those links and looking at this
ostream& operator<< (int val);

i would say that it should work like this
operator<<(x);
but it doesnt


Ohh but it works like this
cout.operator<<(x);
There is probably no other way to type it right?

Finally understood what u meant with
If the OP is a member function of the typeof(lhs), then it just takes the rhs as parameter.
If the OP is not a member, then it takes both lhs and rhs as parameters.

So thank you a lot man :) At least i think i understood :D
Last edited on
Topic archived. No new replies allowed.