I am reading a C ++ primer. I came across the following code:
#include <iostream>
#include <string>
using namespace std;
class PrintString {
public:
PrintString(ostream &o = cout, char c = ' '): os(o), sep(c) {}
void operator() (const string &s) const { os << s << sep; }
private:
ostream &os;
char sep;
};
int main() {
const PrintString printer;
printer("ABC");
return 0;
}
This code works, but I don’t know why. Below I think it would be great if someone could indicate where I am mistaken ...
Here, "printer" is an const PrintString object, so its data members are constants, so "printer.os" is a const reference to cout. Therefore, we will not be able to write to "printer.os", since writing to cout changes it.
Thanks in advance!
source
share