Question

What are best practices when overloading the << operator. Particularly, how do I distinguish between opearting on a pointer vs an object. Is it kosher for them to both output the same string when fed to <<?

For instance, consider the following code where both Book objects have been initialized

Book b1;
Book* b2;

// initialization stuff

// can both of these output the same representation of a book object?
cout << b1 << endl;
cout << b2 << endl;
Was it helpful?

Solution

how do I distinguish between opearting on a pointer vs an object.

By the signature of the operator<< function:

std::ostream& operator<<(std::ostream&, const Book&); // operates on object
std::ostream& operator<<(std::ostream&, const Book*); // operates on pointer

Is it kosher for them to both output the same string?

It is allowed, but not particularly useful. It is very rare to see the second form implemented. If you are tempted to implement the second form, realize that it is entirely redundant. For example, if you have a Book* pBook:

std::cout << *pBook << "\n";

That will print the object to which pBook points quite nicely.

OTHER TIPS

Don't overload operator<< for pointers-to-T. Instead, overload for T itself (or rather, const T& as appropriate), and dereference the pointer in your call to operator<<.

cout << *b2 << endl;

Overloading for pointer-to-T will just create confusion and potentially name collisions, and isn't necesarry in the first place if you overload for const T&

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top