0
votes

Hi i am reading a book and have one doubt under section of const member funcitons. The code is as follows:

class Screen {
public:
    // display overloaded on whether the object is const or not
    Screen &display(std::ostream &os)
        { do_display(os); return *this; }
    const Screen &display(std::ostream &os) const
        { do_display(os); return *this; }
private:
    // function to do the work of displaying a Screen
    void do_display(std::ostream &os) const
    {os<<contents;}

};

My question is at the last line, it is written that os<<contents but since do_display is a const member function how can it modify the data member contents which is of type std::string? Again contents is a private data member of the class Screen and as you can see in the example contents has been changed inside a const member function. How is this happening ? Doesn't const mean that we can't change any data member of the class? Is there a typo in the book or am i missing something? For reference i am attaching the screenshot from the book where i have highlighted this part.

Screenshot 1

1
That statement reads from contents. os is "modified", not contents.Mat
"as you can see in the example contents has been changed...", no, I don't see that it has.Mooing Duck

1 Answers

1
votes

Since os is not a member of your class, that’s not a problem. The classes’ members are not changed in that statement.

The contents member is only read, not modified.