/    /  CPP – Const Arguments

Const Arguments

 

The constant variable can be declared with a const keyword. The keyword const renders the variable value stable. The constant variable must be initialized when declaring.

The const keywords can be used with: Variables, Pointers, Function Arguments and Return Types, Class Data Members, Class Member Functions, and Objects.

 

For example

int x=5;
const int a = 10; // the value of a is constant, a++ is illegal.
const int * v=&x; or int const * v=&x; // pointer to constant, *v=2 is illegal.


(These types of pointers are those which cannot change the value they are pointing at.)

int * const w = &x; // constant pointer, w++ is illegal.

 

(These types of pointers are those which cannot change the address they are pointing at.)
const int * const z = &x; // constant pointer toward a constant.

 

Const Member Functions: If a member function does not modify any data in the class, we can declare it as a member function const as follows-

✓ void mul(int, int ) const;

✓ double getbalence( ) const;

The qualification const is attached to the function prototypes in the declaration and definition.

The compiler will generate an error message if the function attempts to change the data values.