a06e
a06e

Reputation: 20774

What's the use of const variable members in C++?

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.

Upvotes: 2

Views: 131

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145194

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.

Upvotes: 2

Razib
Razib

Reputation: 11153

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;

Upvotes: 0

Related Questions