Categories: C++

const keyword in C++

Const keyword define constant values that cannot change while the program is running. A const variable must be assigned a value when it is declared.

If we try to change its value after it has been initialized, we will get a compilation error.

Use of const keyword with different parameters:

  • Variables
  • Pointers
  • Function arguments and return types
  • Class Data members
  • Class Member functions
  • Objects
const variable:

It is a const variable that is used to define variable values that will never change during program execution—and attempting to change the value results in an error. For instance,


#include <iostream>
using namespace std;

// Driver Code
int main()
{

 const int y = 10;
 cout << y;
    //y=11;
 return 0;
}

the output will be 10 in this case, but if remove the comments then we will get an error message:

/tmp/V7dAvdWEIa.cpp: In function 'int main()':
/tmp/V7dAvdWEIa.cpp:11:6: error: assignment of read-only variable 'y'
   11 |     y=11;
      |     ~^~~
Const pointer:

To make a const pointer, precede the pointer’s name with the const keyword. We cannot change the address of the const pointer after it has been initialized, so the pointer will always point to the same address once it has been initialized as a const pointer.

Also, note that we can apply const to what the pointer is pointing to, or we can make the pointer itself a constant.

const int* a; //a is a pointer that can point to a const int type variable.

Or

int x = 1;
int* const y = &x; // y is a pointer, which is const, that points to an int

We can also have a const pointer pointing to a const variable.

const int* const x;
Example:
#include <iostream>  
using namespace std;  
int main ()  
{  
// declare integer variable  
int x = 7, y = 10;  
  
const int *ptr = &x; // here x become constant variable  
cout << " \n The initial value of ptr:" << *ptr;  
cout << " \n The value of x: " <<x;  
  
// *ptr = 15; It is invalid; we cannot directly assign a value to the ptr variable  
ptr = &y; //  here ptr variable pointing to the non const address 'y'  
  
cout << " \n The value of y: " <<y;  
cout << " \n The value of ptr:" << *ptr;   
return 0;  
}  
Output:
The initial value of ptr:7 
 The value of x: 7 
 The value of y: 10 
 The value of ptr:10
const function Arguments:

Using the const keyword, we can declare the function arguments as constant arguments. And if the value of a function argument is declared const, it cannot be changed.

#include <iostream>  
using namespace std;  
int Test (const int num)  
{  
// if we change the value of the const argument, it thwrows an error.  
// num = num + 10;  
cout << " The value of num: " << num << endl;  
return 0;  
}  
int main ()  
{  
// call function  
Test(5);  
}  
Output:
The value of num: 5
Const Member function of class:

We can create a constant member function of a class by adding the const keyword after the name of the member function. For instance,

#include <iostream>  
using namespace std; 
class Coderz  
{  
  
public:  
int A;  
void fun () const  
{  
 A = 0; // it shows compile time error  
}  
};  
  
int main ()  
{  
    Coderz obj;  
    obj.fun();  
    return 0;  
}  

The above code fails to compile because the fun() function is a const member function of class Coderz and we are attempting to assign a value to its data member ‘A’, which returns an error.

/tmp/V7dAvdWEIa.cpp: In member function 'void Coderz::fun() const':
/tmp/V7dAvdWEIa.cpp:10:4: error: assignment of member 'Coderz::A' in read-only object
   10 |  A = 0; // it shows compile time error
      |  ~~^~~
Class Object as const:

When we use the const keyword to create an object, the value of data members can never change during the object’s lifetime in a program. Const objects are also referred to as read-only objects.

Example:
#include <iostream>  
using namespace std;  
int main ()  
{  
// declare variables  
int r;  
const double PI = 3.14;  
double result;  
cout << " Input the radius of a circle: " << endl;  
cin >> r;  
result = PI * r * r;  
cout << " The area of a circle is: " << result;  
}  
Output:
Input the radius of a circle: 
12
The area of a circle is: 452.16
Const Data Members of class:

Data members are similar to variables declared within a class, but once initialized, they never change, not even in the constructor or destructor. The const keyword is used before the data type inside the class to initialize the constant data member.

#include <iostream>  
using namespace std;  

class Coderz  
{  
  
public:  
 // use const keyword to declare const data member  
const int X;  
// create class constructor  
Coderz ( int y) : X(y)  
{  
cout << " The value of y: " << y << endl;  
}  
};  
int main ()  
{  
Coderz obj( 10); // here 'obj' is the object of class Coderz  
cout << " The value of constant data member 'X' is: " << obj.X << endl;  
// obj.X = 5; // it shows an error.  
// cout << obj.X << endl;  
return 0;  
}  
Output:
The value of y: 10
 The value of constant data member 'X' is: 10

Note: also read about Constructors and Destructors in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago