2

I'm trying to build a custom const_iterator nested class for my Array-based list class. here's the class

class const_iterator { private: const T *p; public: const_iterator(const T *l) { p = l; } const_iterator(const_iterator &ci) { p=ci.p;} const T &operator*() const {return *p;} bool operator==(const iterator &i) const { if(*p==*i) return true; else return false; } bool operator!=(const_iterator &i) const { if(*p!=*i) return true; else return false; } const_iterator &operator=(const_iterator &i) const { p=i.p; return this; } const_iterator &operator++() const { return const_iterator(p+1); } const_iterator &operator--() const { return const_iterator(p-1); } const_iterator operator++(int) const { p = p+1; return const_iterator(p-1); }; const_iterator operator--(int) const { p=p-1; return const_iterator(p+1); } }; 

However, when I go back into my class to make a begin, end, etc. as shown here:

iterator begin() { return iterator(&data[0]); } const_iterator begin() const { return const_iterator(&data[0]); } iterator end() {return iterator(&data[place+1]);} const_iterator end() const {return const_iterator(&data[place+1]);} const_iterator cbegin() const { return const_iterator(&data[0]); } const_iterator cend() const {return const_iterator(&data[place+1]);} 

I get an error: "no matching constructor for initialization of 'ArrayList::const_iterator" on my cbegin and cend. I'm aware it's probably something stupid I don't understand about C++. Thanks in advance for the help!

2
  • And data is ... what exactly? Commented Sep 10, 2014 at 2:24
  • data is the array of type T containing everything in the list. Commented Sep 10, 2014 at 2:25

2 Answers 2

2

Either remove the const_iterator copy constructor (as it is not needed), or make the copy constructor take a const const_iterator&.

Here is a minimal example:

template <typename T> class ArrayList { public: class const_iterator { private: const T *p; public: const_iterator(const T *l) { p = l; } const_iterator(const const_iterator &ci) : p(ci.p) {} }; T data[10]; const_iterator cbegin() const { return const_iterator(&data[0]); } }; int main() { ArrayList<int> a; ArrayList<int>::const_iterator it = a.cbegin(); } 

This compiles here: http://ideone.com/04EE4P

The removal of the copy constructor also compiles with no errors. This indicates that your user-defined copy constructor that takes a non-const reference was causing the issue.

Sign up to request clarification or add additional context in comments.

1 Comment

tl;dr just shove const everywhere you could ever need it. This fixed it. Thank you so much!
1

const_iterator( T *l) should be const_iterator(const T *l)

1 Comment

Tried that, and have reflected it above. Still spits out the same error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.