const and immutable member variables in classes

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 3 00:11:00 PST 2016


On Wednesday, 3 February 2016 at 06:11:07 UTC, H. S. Teoh wrote:
> I still can't come up with a compelling use case that would 
> justify using a const/immutable class member, that couldn't be 
> done by some other means, though. Especially since we're 
> talking about classes, we already have all the traditional OO 
> mechanisms for controlling access to members - get methods, and 
> so on, which are more flexible and adaptable to different use 
> cases to begin with (e.g., can be overridden by derived 
> classes, can implement custom access criteria not expressible 
> by const/immutable, etc.), so I have a hard time justifying 
> using const/immutable members instead.

You make a member variable const or immutable for the same 
reasons that you make a local variable const or immutable - it 
prevents accidental mutation and potentially makes it so that the 
compiler can optimize your code better. It's not necessarily the 
case that a const or immutable member variable is exposed in the 
API. It could be purely internal, or it could be exposed via a 
property function like any other member variable (I tend to think 
that member variable should never be exposed except for POD 
structs, since you lose out on flexibility if you do). But by 
simply making it const or immutable, you avoid certain bugs and 
potentially get faster code. IMHO, ideally, any variable that's 
never going to be mutated would be const or immutable, but that's 
not always possible for a variety of reasons (e.g. it doesn't 
play well with struct members, and const doesn't work well with 
all types).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list