const attribute in class, should be public or protected?
I have some attributes which are const,开发者_JAVA百科 so should these attributes be made public or protected ?
I was in support of protected because it is used by some of the derived classes, but my friend argued that since it is const, it doesnt make any difference even if it is public, which also makes some sense.
But, as I learnt cpp, I thought if possible, we should try to make attributes protected or private and use accessors to change them ??
Thanks.
I think that they should be private or protected if they are irrelevant to the external interface. If you make them public, someone may use them. If you change the implementation and the constants go away... oops!
You make them public if you want other classes to be able to use them. You make them protected if only the classes in your hierarchy need them and you want to keep from cluttering your program's namespace unnecessarily.
If it's a constant, it's pretty silly to make a read accessor for it. And a write accessor wouldn't work. So don't bother.
精彩评论