Reputation: 2956
template<class T>
class Vector {
size_t size;
size_t allocated;
T *array;
public:
Vector() {...};
Vector(size_t constr_size) {...};
Vector(const Vector &source) {...};
~Vector() {
delete array;
};
/*omitted methods*/
class iterator : public std::iterator<std::input_iterator_tag, int> {
Vector<T> *vector;
size_t position;
public:
iterator(Vector<T> *vector_, size_t idx) {
vector = vector_;
position = idx;
};
iterator(iterator &it) {
vector = it.vector;
position = it.position;
};
/*more omitted methods*/
};
Vector<T>::iterator begin() {
return Vector<T>::iterator(this, 0);
};
Vector<T>::iterator end() {
return Vector<T>::iterator(this, size);
};
};
When I try to create a Vector and work with iterators I get an error No matching constructor for initialization of 'Vector::iterator'. Why does it happen? Seems like all required fields are defined, yet somehow I get an error.
Upvotes: 1
Views: 620
Reputation: 65620
Vector<T>::iterator begin() {
return Vector<T>::iterator(this, 0);
};
Since you return by value here, the copy constructor for iterator
will be called. That looks like this:
iterator(iterator &it);
Note that you are trying to copy-construct using a temporary (Vector<T>::iterator(this,0)
), but the copy constructor takes its argument by non-const reference. You can't bind a temporary to a non-const reference, hence the error.
The simple fix is to make the copy constructor take a const reference:
iterator(const iterator &it);
Upvotes: 5