Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2005
    Thanked 1 Time in 1 Post

    Question Why is the constructor of my Iterator class PRIVATE within my List class? [C++]

    I am working on an assignment where I need to implement my own templated Linked List with a corresponding Iterator class, and one of the requirements has me a little confused...
    Within the public section of the LIST class I define my ITERATOR class and there is a requirement that its constructor be PRIVATE find below the code itself.

    template<typename T>
    class List
       class Iterator
       friend class List<T>;
          Iterator() : current(NULL), List(NULL);	// default constructor
          ... all the operator overloads ...
          Node<T>       *current;
          const List<T> *List;
          // ??? private constructor. Why? ???
          Iterator(const List<T> * List, Node<T> *p)
             : List( List ), current( p ){}
    So, I can't seem to explain why the iterator non-default construtor has to be PRIVATE - the course tutor said because it needs to be a singleton but I don't see why that is the case, it is my understanding that you want to be able to create multiple instances of iterator for the same like (like a [first,last) combo for example) - so how does this make any sense?

    Any help or hints would be much appreciated, anyone have a clue why the constructor needs to be PRIVATE?

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Thanked 328 Times in 324 Posts
    Well the reason it would be private is that you only want the user to create an iterator for the list by calling a function on the list that returns an iterator for that list. A singleton is a whole different thing (though they do have private constructors too) and not related to iterators.

    That's just one approach, you could make a more generic iterator that wouldn't be a sub class that you could pass it a list and it would create an iterator for it. In that case you wouldn't have a private constructor.

    Does that make sense?


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts