We’ve seen how to overload an operator in C++. The stream operators are similar in nature, however, they can be a bit more involved.
In many languages, there is a default toString() method for your classes, which lets the language know how to connect to the string. However, there isn’t one in C++, so we can override the << operator though with similar effect.
We need to think about how this will take place. Do we want just plain simple data? Or do we need to specify extra information, like what class it is?
The first issue we run into however is that << is an operator for the output stream class, not the Circle class, or any other class we’d write. Therefore, we’ll have to work with build a friend.
A friend function is defined by putting friend in front of the function definition, and it lets it have access to the objects data because it is considered trusted. This will need to be put into the header.
friend ostream& operator<<(ostream& out, const Circle& c);
Note that you are returning an ostream&, which allows you to chain multiple items together like:
cout << "This circle has a radius of: " << c.getRadius() << endl;
This also means you will need to include two lines of code at the top of the header file. One for working with streams, or specifically the output stream in this case, and the other being the namespace.
#include <iostream>
using namespace std;
These will not need to be in the cpp file, since the file imports the header file where these are already defined.
Inside of the cpp file we’ll write our function, however, you’ll notice a couple of differences. First there is no Circle::, this is because it is not part of the circle class, but part of the output stream. Second, friend is only used in the prototype.
ostream& operator<<(ostream& out, const Circle& c)
{
out << "A circle with a radius of: " << c.radius;
return out;
}
If you wanted to override the input stream operator, you’d find a similar process except using istream instead of ostream.
Overriding the output stream operator was originally found on Access 2 Learn