Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are STL's iterators exposing their container's internals? Why are iterator's member variables mostly public?

std::list‘s iterator is a struct, not a class.

In some implementations, it has the node pointer public and accessible to the user. Therefore, a user should be able to "accidentally" modify a link and break the relationships within the list through an iterator. Why is this possible?

I do get that the member functions of containers (the ones that modify the container) frequently need to extract the underlying pointers from the iterators, but can’t the container itself be a friend to the iterator? And the internals of it [the iterator] be declared private?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Doesn’t this violate encapsulation and OOP principles?

Can you explain the logic behind this decision? Why doesn’t the standard require the iterators’ internals to be private?

>Solution :

Why are STL’s iterators exposing their container’s internals?

They don’t.

Why doesn’t the standard require the iterators’ internals to be private?

Because that would be of no gain. The standard does not specify that the members are publicly accessible and that should be enough to know that you shall not write code that assumes the members are publicly accessible.

If you are working with an implementation where the members are public and you do access them then you are relying on implementation details and your code is not portable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading