The std::ostream such as std::cout is just a binary function operator<<
.
For most pointers, the fallback just prints its address.
But char const*
is printed expecting a C-style string or C-style string literal. ostream& operator<<(ostream&, char const*);
prints the characters until a '\0'
stops the loop.
You can simulate that behavior with some simple structs:
#include <iostream>
using std::cout;
using std::ostream;
namespace {
struct Coord { int x; int y; };
struct Stuff { int x; int y; };
ostream& operator<<(ostream& out, Coord const& coord) {
out << coord.x << ", " << coord.y;
return out;
}
ostream& operator<<(ostream& out, Coord const* p) {
out << p->x << ", " << p->y;
return out;
}
ostream& operator<<(ostream& out, Stuff const& stuff) {
out << stuff.x << ", " << stuff.y;
return out;
}
} // anon
int main() {
auto coord = Coord{10, 20};
auto stuff = Stuff{30, 40};
auto pcoord = &coord;
auto pstuff = &stuff;
cout << "Coord: " << coord << "\n";
cout << "PCoord: " << pcoord << "\n";
cout << "Stuff: " << stuff << "\n";
cout << "PStuff: " << pstuff << "\n";
}
Which has the output:
Coord: 10, 20
PCoord: 10, 20
Stuff: 30, 40
PStuff: 0x7ffeeaa06a88