Reputation: 135
Recently in class we were taught about the STL iterator to traverse through lists. In the example code given for a basic Iterator for a linked list I came across something that I couldn't make sense of.
We were given 2 Iterator classes, const_iterator and iterator. They were both sub-classes of the List class. iterator inherited from const_iterator. In the constructor of iterator I'm not sure why it was written like this;
iterator class:
class iterator:public const_iterator{
friend sortedList
protected:
iterator(Node* n):const_iterator(n){}
public:
iterator(){
n = nullptr;
}
The const_iterator class:
class const_iterator {
friend SortedList
protected:
Node* curr_;
const_iterator(Node* n){
curr_ = n;
}
public:
const_iterator(){
curr_ = nullptr;
}
My question is why does iterator inherit from const_iterator and why is iterator's constructor initializing the const_iterator ctor and doing nothing to itself.
Side question; when accessing curr_ from iterator how would I refer to it? Would I just call curr_ or would I use this->curr_?
Upvotes: 0
Views: 108
Reputation: 92261
My question is why does iterator inherit from const_iterator and why is iterator's constructor initializing the const_iterator ctor and doing nothing to itself.
There is a requirement for the standard containers that iterator
is convertible to const_iterator
. Deriving one from the other is one way of achieving this.
The const_iterator
base class stores a pointer to a Node
but the iterator
does not, so passing the parameter on to the base class will initialize the curr_
member that both base and derived can use.
when accessing curr_ from iterator how would I refer to it? Would I just call curr_ or would I use this->curr_?
You can use curr_
both in the base class and the derived as long as there is no question about whether it is a member variable or not. The fact that the name ends in an underscore is a common convention for member variable names.
If there is any doubt about he scope, you can use this->member
to make it obvious that you refer to a member of the class.
Using this->
when it really isn't needed is deemed extra confusing by some people (like me) so should probably be saved for cases where there is a real need to disambiguate a name.
Upvotes: 2