Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I expose a protected std::vector?

Tags:

c++

I have a class which I intend for others to inherit from. It has a std::vector which I only want developers to be able to read from, but not modify, my base functions modify it. Should I provide a function that returns a const iterator, or expose the vector as protected.

Thanks

like image 476
jmasterx Avatar asked Dec 10 '22 10:12

jmasterx


2 Answers

If you expose the vector as protected, subclasses will be able to modify it. So, you should expose methods that return const iterators.

You can use the Non-Virtual Interface idiom to expose different interfaces for users and subclasses.

like image 108
Björn Pollex Avatar answered Dec 11 '22 22:12

Björn Pollex


If you protected it, then you lose your protection because any subclass can change it to public and let others to modify it.

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

like image 31
Shuo Avatar answered Dec 12 '22 00:12

Shuo