lundi 1 juin 2015

Returning iterator from constant member function

In the following code why the return type of foo::func is vector<int>::const_iterator and not vector<int>::iterator though I am returning an object of vector<int>::iterator.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class foo
{
private:
  vector<int> ar;
public:
  foo()
  {
    ar.resize(10);
    iota(ar.begin(), ar.end(), 1);
  }
  auto func() const
  {
    return ar.begin() + 5;
  }
};

int main()
{
  foo x;
  cout<<boolalpha<<endl;
  auto it = x.func();
  cout<<is_same<decltype(it), vector<int>::iterator>::value<<endl;
  cout<<is_same<decltype(it), vector<int>::const_iterator>::value<<endl;
  return 0;
}

Output of above code is :

false
true

Instead if I redefine foo::func() as

auto func()
{
    return ar.begin() + 5;
}

The output will be

true
false

Why the constant member function is changing return type to constant? And should I need to remove const keyword to make the return type as vector<int>::iterator or is there any other way?

Aucun commentaire:

Enregistrer un commentaire