3

Suppose I have a constant member and different object have different values for this constant, what is the difference between this constant member and a private member without a setter?

samnaction
  • 1,194
  • 1
  • 17
  • 45
  • 6
    A private member without a setter can be still changed by the class internally, while a const member cannot. – πάντα ῥεῖ Jul 16 '18 at 06:26
  • 1
    "...by the class internally" *or by a `friend` function*. – BoBTFish Jul 16 '18 at 06:29
  • Very little, it's mostly a matter of style. However you can do things with a public constant that you can't with a private variable and a getter. For instance you could take the address of the constant, or use sizeof on it. Writing classes is (in part) about defining the interface to the class that you expect to be used. This is why a getter is preferred. A class with a well defined interface is also easier to modify at a later date. – john Jul 16 '18 at 06:30
  • If you have tried above, can you provide a code snippet? What behaviour you are getting? I mean how are you assigning different values to this constant for different instances? –  Jul 16 '18 at 06:39
  • @john, the difference is actyually very big, as pablo285 points out in his answer. There is a "little" difference only if your class never change the value of it's private member after initialization, but this is quite a corner case. – Gian Paolo Jul 16 '18 at 07:37

1 Answers1

4

Apart from cv-qualification and accessibility being two completely different concepts there are also practical implications to const public member vs private non-const member.

  • private members cannot be reached outside of their object so you will have to create a public method (getter) if you want to do that
  • private non-const member is mutable, i.e. methods defined in the same class can change it
  • const member cannot be changed once you initialize it

It all depends on what you want to do.

pablo285
  • 2,460
  • 4
  • 14
  • 38