The article provide short summary on the cases of const usage in c++. More cases and examples can be founded at wiki and at the const: why & how article.
The main idea of using ‘const’ is to help a compiler to optimize the program. Let’s go through the use cases:
1. Declare a named constant
The most typical and trivial case. Such constants are useful for parameters which will not need to be changed after the program is compiled.
const int Constant1 = 96;
2. Used for pointers
‘const’ applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right).
const int * Constant2 // declares that Constant2 is a variable pointer to a constant integer
int const * Constant2
int * const Constant3 // declares that Constant3 is constant pointer to a variable integer
int const * const Constant4 // declares that Constant4 is constant pointer to a constant integer
int val = 5;
const int* changedPtrConstVal = nullptr;
changedPtrConstVal = &val;
// *changedPtrConstVal = 6; // not legal
int* const constPtrChangedVal2 = &val;
*constPtrChangedVal2 = 6;
// constPtrChangedVal2 = nullptr; // not legal
const int* const constPtrConstVal3 = &val;
// *constPtrConstVal3 = 7; // not legal
// constPtrConstVal3 = nullptr; // not legal
3. Return constant strings
const char* Function2()
{
return "some text";
}
const char* tString = nullptr;
tString = Function2();
printf("%s\n", tString);
4. In parameters passing
The variable to be passed without copying but stop it from then being altered.
void Subroutine4(big_structure_type const &Parameter1);
5. At class method
To check that method cannot be called when object is passed as const reference
class C
{
private:
int i;
public:
int Get() const // Note the "const" tag
{ return i; }
void Set(int j) // Note the lack of "const"
{ i = j; }
};
void Foo(C& nonConstC, C const& constC)
{
int y = nonConstC.Get(); // Ok
int x = constC.Get(); // Ok: Get() is const
nonConstC.Set(10); // Ok: nonConstC is modifiable
constC.Set(10); // Error! Set() is a non-const method and constC is a const-qualified object
}