What is const pointer and const reference? - C++

What is const pointer and const reference?

- const pointer is a pointer which you don’t want to be pointed to a different value. That is, the location stored in the pointer can not change. We can not change where the pointer points.
- It is declared as :
type * const name
type is data type
name is name of the pointer
Example :
char * const p
- Since the location to which a const pointer points to can not be changed, the following code :
char ch1 = ‘A’;
char ch2 = ‘B’;
char * const p = &ch1;
p = &ch2;
will throw an error since address stored in p can not be changed.
const reference :
- const references allow you to specify that the data referred to won't be changed. A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it’s a reference to const. Once a reference is bound to refer to an object, it can not be bound to refer to another object.
- For example :
int &ri = i;
binds ri to refer to i.
Then assignment such as:
ri = j;
doesn’t bind ri to j. It assigns the value in j to the object referenced by ri, ie i;
- This means, if we pass arguments to a function by const references; the function can not change the value stored in those references. This allows us to use const references as a simple and immediate way of improving performance for any function that currently takes objects by value without having to worry that your function might modify the data. The compiler will throw an error if the function tries to modify the value of a const reference.
What is NULL pointer and void pointer and what is their use?
What is NULL pointer and void pointer and what is their use? - A NULL pointer has a fixed reserved value that is not zero or space, which indicates that no object is referred.....
Difference between pass by value and pass by reference - C++
Difference between pass by value and pass by reference - In pass by value approach, the called function creates another copies of the variables passes as arguments.....
What are references in C++? What is a local reference?
What are references in C++? - A restricted type of pointer in C++ is known as a reference...
Post your comment