Curious
Curious

Reputation: 553

const attribute in class, should be public or protected?

I have some attributes which are const, 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.

Upvotes: 0

Views: 1538

Answers (2)

Richard Pennington
Richard Pennington

Reputation: 19965

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!

Upvotes: 4

Carl Smotricz
Carl Smotricz

Reputation: 67760

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.

Upvotes: 2

Related Questions