3

Are there any scenarios where a const variable member is useful in C++?

If you want to make an immutable class, the usual approach is to declare private members with get-only const functions to access their values. This has the advantage that the class can be copy assigned and so on. So in this case you don't need const variable members.

On the other hand, if the class has a const member variable, it won't get an automatic copy assignment operator. I don't see an scenario where this would be useful.

4
  • 4
    "If you want to make an immutable object, the usual approach is to declare private member with get-only const functions to access their values." Where did you hear that? Commented Jun 7, 2015 at 18:46
  • "This has the advantage that the class can be copy assigned" if you want an object to remain constant, that's a disadvantage. It's a point of failure. Commented Jun 7, 2015 at 18:49
  • If you can assign a new value to an object, it's not immutable. Commented Jun 7, 2015 at 19:51
  • @LightnessRacesinOrbit I think the confussion was because I used "object" instead of "class". I fixed that. Commented Jun 7, 2015 at 20:06

2 Answers 2

2

A main advantage of a const data member is the same as with a reference member (indeed a reference can be usefully thought of as a const pointer), namely that it forces initialization, unless the member is of a type with a user-defined default constructor. The compiler will insist on initialization. Still, I've never found that so useful that I've started doing it.

An alternative, if guaranteed initialization is what one desires, is to wrap the data member in a class that does not provide default construction. With this approach the data member can be assigned to, if it supports assignment.

Another advantage (of a const data member) is that it expresses an intended constraint, with compiler checking, and that's almost always good. The more constraints on how values can change, the less there is to consider to understand or debug the code.

Sign up to request clarification or add additional context in comments.

Comments

0

Once you initialize a variable const then you never can re-initialized it. Each later attempt to re-initialize the const variable will produce a compilation error.

It is helpful when you want to prevent the accidental modification of some variable which you never want to be change. Like in mathematics we need PI, we can declared it as a constant -

private const double PI = 3.1416;

1 Comment

Comments purged as they were not constructive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.