It's undefined behavior that sometimes works (by luck), sometimes doesn't.
You're returning a pointer to a temporary local object. The pointer to a temporary local object being the internals of the string object obtained by calling os.str().c_str()
.
If you want print those objects easily by cout
, you can overload operator <<
for output streams. Like:
ostream& operator<<(ostream& out, const Vector &a)
{
std::ostringstream os;
os << "Vector(" << a.getX() << "," << a.getY() << ")";
out << os.str();
return out;
}
and then
std::cout << w1 << std::endl;
std::cout << w2 << std::endl;