Should I open a protected std :: vector?

I have a class that I intend to inherit from others. It has a std :: vector that I want developers to be able to read but not modify, my core functions change it. Should I provide a function that returns a constant iterator, or set the vector as protected.

thanks

+4
source share
4 answers

If you expose a vector as protected, subclasses will be able to modify it. So you have to expose methods that return constant iterators.

You can use idioms of a non-virtual interface to expose different interfaces for users and subclasses.

+9
source

If you protect it, you will lose your protection because any subclass can change it for the public and allow others to change it.

Why not provide a reference to a constant? If return const iterator, you may need to rewrite many interfaces, including start, end, size, etc.

+4
source

If you don't want the derived class to modify the vector, I think the answer is straightforward: provide a function to return a read-only iterator!

The returned iterator also encapsulates the base class, which is obviously a good idea.

+1
source

Cons for its protection: cannot easily change to another container, loss of control over allowed operations, coding for implementation instead of an interface, it is more difficult to test

Cons for the returning iterator of the function: a bit of extra input (maybe less than it took to ask this question)

It seems to me the obvious answer.

0
source

Source: https://habr.com/ru/post/1343318/


All Articles