jmasterx
jmasterx

Reputation: 54103

How does STL return 2 iterators with the same function?

I noticed that vector.begin() will return a const iterator, or an iterator based on what is given on the left. How is something like this implemented since the arguments given to the function are the same.

Thanks

Upvotes: 1

Views: 152

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Its return-type is based on whether the vector itself is being accessed through a const reference (or pointer) or not. Also, an iterator can be implicitly converted to a const_iterator, which is why something like this works: std::vector<T> v; std::vector<T>::const_iterator it = v.begin();.

Upvotes: 9

Peter Alexander
Peter Alexander

Reputation: 54270

They are overloaded on the const-ness of the member function:

struct Foo
{
    int bar() { return 1; }
    int bar() const { return 2; }
};

int main()
{
    Foo a;
    const Foo b;
    assert(a.bar() == 1);
    assert(b.bar() == 2);
}

Upvotes: 3

fredoverflow
fredoverflow

Reputation: 263088

begin() and end() are overloaded on the const-ness of *this, something like:

iterator begin();
const_iterator begin() const;

iterator end();
const_iterator end() const;

Upvotes: 5

Related Questions