In c++, what is a better way in protected or setter/getter?

When I use a member variable of a base class in a derived class, what is a better way? or what is the more preferred?

1. using protected
2. using setter/getter

I think If I need read-only data, then using getter is better
but if I need both read and write, then using protected is better.
Last edited on
In broad terms 'protected' was invented for derived classes while getters and setters are there for strict data-hiding purposes

https://en.cppreference.com/w/cpp/language/access
@againtry
thank you!
honestly, in my opinion, using protected is definitely more convenient..
honestly, in my opinion, using protected is definitely more convenient..


But it can break your code. Read up about on Stack Overflow and here:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-class
CoreGuidelines:
C.133: Avoid protected data

Reason protected data is a source of complexity and errors. protected data complicates the statement of invariants....
...
Note: Protected data often looks tempting to enable arbitrary improvements through derivation. Often, what you get is unprincipled changes and errors. Prefer private data with a well-specified and enforced invariant. Alternative, and often better, keep data out of any class used as an interface.

Note Protected member function can be just fine.

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-protected



Sutter and Alexandrescu in 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices'
41. Make data members private, except in behaviorless aggregates
...
Protected data has all the drawbacks of public data, because having protected data still means that an abstraction is sharing the responsibility of maintaining some invariant with an unbounded set of codeā€”in this case, with the unbounded set of current and future derived classes. Further, any code can read and modify protected data as easily as public data by deriving a new class and using that to get at the data.
...
Nonprivate data members are almost always inferior to even simple passthrough get/set functions, which allow for robust versioning.

Thanks TIM for the additional information for the expansive comment. We can be sure OP is grateful.
(Sadly, Mother Inferior repeats with redundancy, once was enough)

tell, don't ask
`base' should be responsible of its data
Topic archived. No new replies allowed.