c++methodsiteratorconstantsconst-iterator

c++ returning const reverse iterator from a class method, but method cannot be const?


I am trying to return a const reverse iterator from a class method. But my code doesn't compile when I mark my method as const. Without const the code compiles with no troubles.

Any idea why?

#include <iostream>
#include <vector>

template <class ValueType>
class DynamicDataComponent {
    using ValuesType = std::vector<ValueType>;
    using IteratorType = typename std::vector<ValueType>::reverse_iterator;

public:
    DynamicDataComponent()
    {
        values.push_back(0);
        values.push_back(1);
        values.push_back(2);
        values.push_back(3);
    }

    const IteratorType getRBeginIt() const {
        return values.rbegin();
    }

private:
    ValuesType values;
};

int main() {
    DynamicDataComponent<size_t> dataComponent;
    std::cout << *dataComponent.getRBeginIt() << "\n";
}

Solution

  • You need to define a const-iterator too:

    using ConstIteratorType = std::vector<ValueType>::const_reverse_iterator;
    

    And define your const qualified member function like so:

    ConstIteratorType getRBeginIt() const {
        return values.rbegin(); // or even `return values.crbegin()` to be clear
    }
    

    Note that a const-iterator is not a const iterator. The ConstIteratorType instance returned by getRBeginIt() const isn't const (or else you wouldn't be able to iterate with it), but when you dereference the iterator, it'll return a const ValueType& or const ValueType*.