ipkiss
ipkiss

Reputation: 13651

What if cout is used inside overloaded output operator function?

I have the following code with the overload output operator in it:

class Student 
{
public:
    string name;
    int age;
    Student():name("abc"), age(20){}
    friend ostream& operator<<(ostream&, const Student&);
};
ostream& operator<<(ostream& os, const Student& s)
{
    os << s.name; // Line 1
    return os;
}

I was wondering what the difference if I changed Line 1 into this: cout << s.name?

Upvotes: 0

Views: 136

Answers (2)

Jon
Jon

Reputation: 437434

Then the operator << would advertise that it can output the student's name to any stream, but ignore its parameter and always output to standard out. As an analogy, it would be similar to writing

int multiplyByTwo(int number) {
    return 4;
}

You can see that this is definitely a problem. If you really wanted to always return 4, then the function should have been

int multiplyTwoByTwo() {
    return 4;
}

Of course you cannot make operator << take only one argument because it's a binary operator so that's where the analogy breaks down, but you get the picture.

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258618

It wouldn't call operator << on os, but on cout. cout is also an ostream, but not the only one.

For example, if you wanted to output to a file, you'd have an fstream. And you write

fstream fs;
Student s;
fs << s;

the output wouldn't be printed to the file, but to cout, which isn't what you want.

It's like saying, "you can output a Student to any ostream you want, it's still gonna be printed to the console".

Upvotes: 2

Related Questions