Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nested classes

Status
Not open for further replies.

AtomicChip

Programmer
May 15, 2001
622
CA
Aiight... A question involving good 'ole data structs (...and nested classes, as the title there would hint ;))

Let's say I have a class DoubleLinkedList. Within that class, I have a nested class (Iterator). I want to keep this as close to the STL implementation as possible (this is a lot more for learning than anything else, so please don't ask me why I'm doing it this way instead of just using the STL)...

Code:
namespace ds
{
  template< typename T >
  class DoubleLinkedList
  {
    public:
    class Iterator
    {
      // ...

      Iterator operator+( )
      {
        // i need to be able to access the "m_head" element of the parent class here
      }

      // ... other operators here ...
    };

    // all public DoubleLinkedList methods here (push, pop, etc)...

    private:
    struct Node
    {
      Node * m_head;
      Node * m_tail;
      T m_data;
    }

    Node * m_head;
    int m_length;

    friend class Iterator;
  };
}

My problem right now is that I am unable to access the parent class's private element "m_head" from within the Iterator class... One possible solution that I have come across is to change the Iterator class to a private member, set a public DoubleLinkedList element of type Iterator, passing it the m_head element in the constructor, but as I said, I want to keep this as close to the STL implementation as possible. In other words (in code), DoubleLinkedList< int >::Iterator.

Is there a keyword to access a parent classes' elements? Am I going about this the wrong way? I've looked a bunch on Google and have been unable to find much about implementing your own iterators... Just a lot 'o stuff about how to use the STL's iterators.

Thanks in advance,

-----------------------------------------------
"The night sky over the planet Krikkit is the least interesting sight in the entire universe."
-Hitch Hiker's Guide To The Galaxy
 
Maybe
Code:
friend class Iterator;
should be:
Code:
friend class ds::DoubleLinkedList<T>::Iterator;

Also, what if you tried making the Iterator a separate class instead of nested?
 
Some addition: in C++ nested class has no special rights to access its parent members. The only effect of nesting is nested class name visibility.
So I think cpjust's advice (with friend keyword) is the only way to go...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top