Thursday, March 28, 2013

Types of constant pointers in C++



In C++ there are basic three types of constant pointers exist.
  1. Pointer that pointed to some constant data.
  2. Pointer that constantly pointed to some memory location.
  3. Pointer that constantly pointed to some constant data.

Pointer that pointed to some constant data.

const datatype * pointerName;
dataType const * pointerName

Here the pointer is pointing to some constant data. That means the data pointed by pointer cannot edit using the pointer. As example if pointer "p" pointing to some string "This is a constant string", The pointer "p" cannot use to edit the content "This is a constant string"


Example:If you try with this peace of code

#include <iostream>
using namespace std;

int main(){
 const char * const_data_pointer_1 = NULL;
 const_data_pointer_1 = "This is a constant string";
 const_data_pointer_1[10] = 'A';
 return 0;
}

C++ compiler shows error like

error C3892: 'const_data_pointer_1' : you cannot assign to a variable that is const


Pointer that constantly pointed to some memory location.

dataType * const  pointerName

Here the pointer behave a content, It means once initialize the pointer it cannot change the memory location it pointing to. In previous type, the content pointed by pointer behave as constant. by here the content pointed by pointer allow the edit but the memory location pointed by the pointer cannot change.

Example:If you try with this peace of code.


#include <iostream>
using namespace std;
int main(){
 char * const cont_pointer = "This is not a constant string"; 
 cont_pointer = "This new memory location not allow to point";
 system("pause");
 return 0;
}

C++ compiler shows error like

error C3892: 'cont_pointer' : you cannot assign to a variable that is const


Pointer that constantly pointed to some constant data.

const dataType * const pointerName;
dataType const * const pointerName;

This type pointer also a constant pointer, It means cannot change the memory location pointed by this pointer. And also the content pointed by the pointer also constant, It means the content pointed by the pointer also not allow the alter.

Example:If you try with this peace of code.

#include <iostream>
using namespace std;
int main(){
 char const * const cont_pointer = "This is not a constant string";
 cont_pointer[10] = 'A';
 cont_pointer = "This new memory location not allow to point";
 system("pause");
 return 0;
}

C++ compiler shows error like.
error C3892: 'cont_pointer' : you cannot assign to a variable that is const
error C3892: 'cont_pointer' : you cannot assign to a variable that is const