const Keyword

const Keyword :

  • const keyword specifies that variables’ value is constant and can’t be further modified by programmer in the program.
  • It must be initialised while declaring.
  • Values defined are subject to type checking and can be used in place of constant expression.

Pointer with const :

pointers to const :
const int* u;
int const* v;
It means pointer is pointing to a const variable.

const pointer :

int * const w=&a;
It makes pointer constant but we can change the value at the address it points.

const pointer to const value :
const int * const w=&a;

  • It makes a constant pointer to a constant value.
  • Neither the value at the address nor the variable, the pointer points to, can be changed.

const class data member :

  • Data members are made constant.
  • They are not initialised when they are declared. Their initialisation occurs in constructors.

const objects :
const class_name obj;

  • Its data members are never changed during objects’ lifetime.
  • It can only call it constant member functions.

Mutable keyword is used with member variables of class, which we want to change even if the object is of const type. Hence, mutable data members of a const objects can be modified.

const member function :
return_type func_name() const;

Cannot change the value of the data members later.

const Function Arguments and return types :

  • Const function arguments cannot be modified.
  • Returning const prevents any modification to returned value.
  • If a function has a non-const parameter, it cannot be passed a const argument while making a call.
  • But, a function which has a const type parameter, can be passed a const type argument as well as a non-const argument.

Leave a Reply

Your email address will not be published. Required fields are marked *