Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write to a const reference of ostream

I am reading C++ primer. I encountered 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 is what I think, it would be great if anyone could help to point out where I am wrong...

Here, 'printer' is a const PrintString object, so its data members are const, so 'printer.os' is a const reference to cout. Therefore, we should not be able to write to 'printer.os' since writing to cout changes it.

Thanks in advance!

like image 654
Patrick Avatar asked Mar 18 '23 22:03

Patrick


1 Answers

The reference isn't being modified, only what it refers to. This works the same with a pointer. If you had a pointer to int data member (int*), using it in a const member function would make its type int* const. You aren't able to change the pointer itself, but you can change what it points to. For example:

struct Foo
{
    int a;
    int* p = &a;

    void foo() const
    {
        p = new int; // ERROR! Not allowed to modify const pointer
        *p = 100; // OK, it's a pointer to a non-const int
    }
};

So when using os, you're only modifying the object that it refers to, not the reference itself.

like image 94
David G Avatar answered Mar 29 '23 15:03

David G