C++ Foundation - const Keyword

1. Introduction to const

Const is a type modifier commonly used in C++. A common type refers to a type specified by the type modifier const. The value of a variable or object of a constant type cannot be changed.
The difference between const and # define:
(1) const can specify the type explicitly.
(2) const can use the scope of C++ to restrict definitions to specific functions or files.
(3) const can be used for more complex types

Constant variable const Type Variable Name/Type const Variable Name const int a / int const a
Frequently cited const - Type - Reference Name / Type - const & Reference Name const int &a / int const &a
Constant object Class name const object name / const class name object name A const a / const A a
Constant member function Class name: function (parameter) const A::a(int b) const
Constant group Type const Array Name [Size]/Const Type Array Name [Size] int const a[num] / const int a[num]
Constant pointer const * pointer name [pointer refers to a constant] const int* a
Type * const pointer name [pointer itself is a constant] int* const a
Const type * const pointer name [constant pointer to constant] const int* const a

1.1 Constant Variable
(1) const variables (objects) must be initialized when they are created, and their values cannot be changed once they are created.

const int i=0; //i cannot change the value and must be initialized when defined
i=1; //Errors will be reported. Constants cannot change values.
const int j; //Error reporting, no initialization

(2) Const objects are valid only in a single file, and the same name const variables of multiple files are independent variables. To solve this problem, extern is used to define and declare const variables.

// In. c, a constant is defined and initialized, which can be accessed by other files.
extern const int i=0;
// Other. h header files
extern const int i;

1.2 Frequently cited
Constants can be assigned to references to constants, but constants cannot be assigned to references to variables.

int d=10;
const int e=15;
const int &a=d; //Assigning a non-constant value to a constant reference cannot modify the value of reference a at this time, but when the value of d is modified, the value of reference a is also modified.
const int &f=e; //_Assigning constants to quotations of constants

const int &b=a; // References are not objects and cannot have references
f=10;       //X cannot change the value of a constant reference
int &c=e;   //X cannot assign constants to references to variables

1.3 Constant Objects and Constant Membership Functions
When member functions of classes are defined, there are often some member functions that do not change the data members of classes. In order to improve program security, the member functions of classes that do not change are usually defined as constant member functions, and the member functions are changed into "read-only" functions.
(1) Const member functions should be const qualified in both the function prototype description (.cpp) and the function definition (.h)
(2) Constant member functions cannot be called by constant member objects
(3) The values of all member variables of a constant object can not be changed, and non-const functions can not be invoked, except for the system call constructor (to modify the values of member variables, only in the constructor, and through the initialization list).

class A{
    int x;   
    public:
        A(){    //Constructor 
            x=10;
         }
        int getX() const{   //The member function does not change the class, so it is set to a const member function 
            return x;
        }
        void setX(int a){  //Membership functions change classes
            this->x=a;
        }
};

int main(){
    A a;
    a.setX(15);   //Constant member functions cannot be called by constant member objects 
    cout<<"a "<<a.getX()<<endl;
    const A b; 
    cout<<" b "<<b.getX()<<endl;   //Constant object calls constant member function, must be initialized (constructor), and analog constant variable must be initialized.
/*The values of all member variables of a constant object cannot be changed.
    The non-const function cannot be called except the system call constructor.
    To modify the value of a member variable, only in the constructor, and by initializing the list*/
 } 

1.4 Constant Group
In the parameter transfer process of an array, the parameter passes the address of the first element of the array.
If there is a const array, prohibiting assigning the address of the constant array to the non-constant pointer means that the array name cannot be passed as a parameter to a function using non-constant parameters.

const int months[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int sum(int arr[],int n);  //Function prototype
...
int j=sum(months,12);  //* Constant array addresses cannot pass array names as parameters to functions that use non-constant parameters

1.5 Constant Pointer
The pointer itself is the address of the variable, as shown in the following figure:
 

(1) const type * pointer name [pointer refers to a constant]
const is on the left side of * to indicate that the pointer refers to a constant. At this time, the variable on the address can not be changed, and the address can be changed. Different addresses correspond to different data.

int i=1;
int ii=2;
const int * str=&i;  //The pointer refers to a constant, where str points to the address of the i variable
cout<<"1 "<<*str<<endl;  //At this point the output is 1.
str=&ii;   //This sentence indicates the address where str points to the ii variable. It only modifies the pointer address, not the content of the pointer.
*str=ii;   //This sentence modifies the content of the pointer
cout<<"2 "<<*str<<endl;  //At this point, the output of the variable on the ii address, the result is 2

(2) Type * const pointer name [pointer itself is a constant]
const is on the right side of * to indicate that the pointer itself is a constant. At this time, the address of the pointer cannot be changed, and the variables on the address can be changed.

int i=1;
int ii=2;
int * const str=&i;  //The pointer itself is a constant, where str points to the address of the i variable
cout<<"1 "<<*str<<endl;  //At this point the output is 1.
str=&ii;   //This sentence modifies the address of the pointer
*str=ii;   //This sentence only modifies the content of the pointer, not the address of the pointer.
cout<<"2 "<<*str<<endl;  //At this point, the output of the variable on the ii address, the result is 2

(3) Const type * const pointer name [constant pointer to constant]
At this time, you cannot modify the address of the pointer or the variables on the address.

int i=1;
int ii=2;
const int* const str=&i;  //The pointer itself is a constant, where str points to the address of the i variable
cout<<"1 "<<*str<<endl;  //At this point the output is 1.
str=&ii;   //This sentence modifies the address of the pointer
*str=ii;   //This sentence modifies the content of the pointer

2. const should be used whenever possible

  • Using const avoids programming errors that unintentionally modify data
  • Using const enables functions to handle const and non-const arguments, otherwise they will only accept non-const data.
  • Using const references is a function that correctly generates and uses temporary variables

Keywords: Programming

Added by twmcmahan on Mon, 26 Aug 2019 16:59:17 +0300