Difference between Pointers and References in C++
1. You can assign a pointer variable multiple times, but the same cannot be done with a reference variable. It should be assigned only during initialization.
Eg:
Re Assigning Pointer variables can be possible
int num1 = 10;
int num2 = 20;
int *ptr = &num1;
ptr = &num2;
Re Assigning Reference variables is not possible
int num1 = 10;
int num2 = 20;
int &ref;
ref = num2; //Error
2. You have to use * operator to dereference a pointer variable, but there is no need of any operator to dereference a reference variable(Automatic Indirection), you can directly use it as a normal variable.
3. You can have multiple levels of indirections in pointers(i.e., pointer to pointer to pointer) but the same cannot be done with references. with references there is only one level of indirection.
int num1 = 10;
int *ptr = &num1;
int **ptr = &ptr;
int &refer = num1;
int &&rrefer = refer; //Error
4. Pointers can be assigned NULL, but if you try the same with reference it will throw an compiler error
int *ptr = NULL;
int &refer = NULL; //Error
5. Pointer is a variable that has separate address when compared to the variable it is referencing whereas reference will have the same address to which it is pointing to
int number1 = 10;
int *pointer = &number1;
int &refer = number1;
cout << "Number1 Address: "<<&number1<<endl;
cout << "Pointer Address: " <<&pointer <<endl;
cout << "Reference Address:"<<&refer<<endl;
You can observe number1 and refer address will be same .
Eg:
Re Assigning Pointer variables can be possible
int num1 = 10;
int num2 = 20;
int *ptr = &num1;
ptr = &num2;
Re Assigning Reference variables is not possible
int num1 = 10;
int num2 = 20;
int &ref;
ref = num2; //Error
2. You have to use * operator to dereference a pointer variable, but there is no need of any operator to dereference a reference variable(Automatic Indirection), you can directly use it as a normal variable.
3. You can have multiple levels of indirections in pointers(i.e., pointer to pointer to pointer) but the same cannot be done with references. with references there is only one level of indirection.
int num1 = 10;
int *ptr = &num1;
int **ptr = &ptr;
int &refer = num1;
int &&rrefer = refer; //Error
4. Pointers can be assigned NULL, but if you try the same with reference it will throw an compiler error
int *ptr = NULL;
int &refer = NULL; //Error
5. Pointer is a variable that has separate address when compared to the variable it is referencing whereas reference will have the same address to which it is pointing to
int number1 = 10;
int *pointer = &number1;
int &refer = number1;
cout << "Number1 Address: "<<&number1<<endl;
cout << "Pointer Address: " <<&pointer <<endl;
cout << "Reference Address:"<<&refer<<endl;
You can observe number1 and refer address will be same .
Comments
Post a Comment