Reputation: 1862
I am learning operator overloading recently. I don't know why cout
is outputting nothing after I add const
keyword for ostream
in argument list. Does this have something to do with the addition of that keyword? the code is as follows:
Program1:
#include<iostream>
#include<string>
using namespace std;
class Foo
{
private:
string bar;
public:
Foo(string str);
friend const ostream& operator<<(const ostream& o, const Foo& f);
};
Foo::Foo(string str)
{
this->bar = str;
}
const ostream& operator<<(const ostream& o, const Foo& f)
{
o << f.bar;
return o;
}
int main()
{
Foo f("HelloWorld");
cout << f;
}
output:nothing
Program2 :
#include<iostream>
#include<string>
using namespace std;
class Foo
{
private:
string bar;
public:
Foo(string str);
friend ostream& operator<<(ostream& o, const Foo& f);
};
Foo::Foo(string str)
{
this->bar = str;
}
ostream& operator<<(ostream& o, const Foo& f)
{
o << f.bar;
return o;
}
int main()
{
Foo f("HelloWorld");
cout << f;
}
output:HelloWorld
Upvotes: 0
Views: 233
Reputation: 16725
The problem is caused by const
. Declare your friend function as non-const:
friend ostream& operator<<(ostream& o, const Foo& f);
And implementation:
ostream& operator<<(ostream& o, const Foo& f)
{
o << f.bar;
return o;
}
I can't understand why does this code compile because operator<<
should always change the object. Your code is an undefined behaviour and may cause a segmentation fault.
Upvotes: 3