const and immutable member variables in classes

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 2 22:11:07 PST 2016


On Tue, Feb 02, 2016 at 09:08:07PM -0800, Jonathan M Davis via Digitalmars-d-learn wrote:
> On Tuesday, February 02, 2016 19:32:39 Ali Çehreli via Digitalmars-d-learn wrote:
> > On 02/02/2016 07:05 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
> >  > I usually tell folks not to do it because of all of the problems
> >  > it causes.
> >
> > That's been my guideline: "const and immutable members should be
> > avoided." Now I'm tempted to add this: "only in structs."
> 
> IIRC, I've pretty much always been telling folks specifically to not
> have structs with const or immutable members and haven't generally
> said anything about classes.
> 
> But I really don't see any reason to avoid it in classes at this
> point.  Maybe if a serialization mechanism were involved, it would
> matter, but the class would probably have to be designed to support
> that given that there is no equivalent to the assignment operator for
> the class objects themselves (just their references). Ultimately, it's
> the ability to overwrite the state of the object that's the problem,
> and that simply isn't an issue with class objects under normal
> circumstances.
[...]

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.


T

-- 
The computer is only a tool. Unfortunately, so is the user. -- Armaphine, K5


More information about the Digitalmars-d-learn mailing list