Search code examples
c++fileconstantsoperators

Why does >> operator gives error on const file in C++?


I have this piece of code:

void NeighborsList::insertVertexes(const ifstream & inputFile)
{
    int tempS, tempT;
    for (int i = 0; i < numOfVertexes; i++)
    {
        inputFile >> tempS;
        inputFile >> tempT;
        addEdge(tempS, tempT);
    }
}

where I'm trying to get the input for a file. Once I remove the const in the function parameter - (ifstream & inputFile) it works.


Solution

  • Given a const object or reference, only const operations may be performed. std::istream::operator>> is not a const operation, therefore it may not be used here.

    It makes sense that std::istream::operator>> is not a const operation, because it alters the observable state of the stream. The read position on the file is changed, for example, as well as status indicators like fail and eof.