In C++ what is the difference between pointer variable and reference variable? Please give an example.
The difference between pointer variable and reference variable are:-
Pointer variable | Reference variable | |
1.) | Pointer variable stores address of the variable. | Reference variable refers to variable that already exists but with other name. |
2.) | Pointer variables can assign null value. | Reference variable cannot assign null value. |
3.) | Pointer variable can be referenced by pass by reference. | Reference variable can be referenced by pass by value. |
4.) | Pointer variable may or may not initialized on declaration. | Reference variable must initialized on declaration. |
5.) | Pointer variables are able to have their own address of the memory. | Reference variable is used to share the identical address of the memory that too with the initial variable. |
6.) | Pointer variables are able to have their own size on the stack. | Reference variable are able to take same memory on the stack. |
7.) | Syntax: type *pointer; | Syntax: type &newname =existing name; |
Example :-
Reference variable in C++:
#include<iostream>
using namespace std;
int main()
{
int n = 40;
int& reference = n;
reference = 50;
cout << "n = " << n << endl ;
n = 60;
cout << "reference = " << reference << endl
;
return 0;
}
Output:
n = 50
reference = 60
Pointer variable in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
string animal = "Dog";
string* ptr = &animal;
cout << animal << endl;
cout << &animal << endl;
cout << ptr << endl;
return 0;
}
Output:
Dog
0x7fff4a80d6e0
0x7fff4a80d6e0
Get Answers For Free
Most questions answered within 1 hours.