How to refer to an “owner class” in C++?
Question
I have code that looks like this:
template<class T>
class list
{
public:
class iterator;
};
template<class T>
class list::iterator
{
public:
iterator();
protected:
list* lstptr;
};
list<T>::iterator::iterator()
{
//???
}
I want to make the constructor of list::iterator
to make iterator::lstptr
point to the list it's called from. I.e.:
list xlst;
xlst::iterator xitr;
//xitr.lstptr = xlst
How would I do that?
And also, am I referencing my iterator-constructor right, or should I do something like this:
template<class T>
class list<T>::iterator
{
public:
list<T>::iterator();
protected:
list* lstptr;
};
Solution
You can pass the list to the constructor of iterator:
list xlst;
list::iterator xitr(xlst);
Or, you could make an iterator factory function:
list xlst;
list::iterator xitr = xlst.create_iter();
In the factory function case, the create_iter()
function can use this
to refer to the enclosing list.
OTHER TIPS
Since you don't need to change (reseat) the pointer and there's no need for the NULL value, I would instead use a reference. Also you can use an initializer list when assigning the member variable (and have to if you're using a reference).
template<class T>
class list::iterator
{
public:
iterator( list& parent ) : lstptr( parent ){}
protected:
list& lstptr;
};
And as mentioned before: use a factory method inside the list class to construct objects of type list::iterator.