+ 3
Value type vs reference type:
Can someone please explain the difference between reference type and value type?
1 Antwort
+ 1
Default way of declaring variables in C++ is value type i.e., when we declare a variable, a value can be assigned to it either using assignment operator or through input. The named variable points the memory location where the value is kept which can be alter by the variable name. For example
int a = 10;
is a value type where we are creating an integer variable and assigning value 10 to it which can be changed at any instance of time.
On the other hand reference type declaration provide direct access to the value type variable, as it stores the memory address of a normal variable as its content. Hence with reference type we can alter the value stored at the addressed location. In C language, this task is performed by the use of pointers whereas C++ provides reference operator
using pointers
------------------
int a = 10;
int *ptr = &a;
cout<<a<<endl;
cout<<*p<<endl;
using & operator
---------------------
int a = 10;
int &ptr ;
ptr= a;
cout<<a<<endl;
cout<<p<<endl;
both above snippets will produce the same result
10
10
These are more significant when used with functions
1) Passing by value
- Copy of actual parameter is pass to formal parameter.
- Values of actual parameter remain unchanged.
- Most of the functions fall under this category.
2) Passing by references
- Instead of sending values of actual parameters, their respective
memory addresses are is passed to formal parameters.
- Values of actual parameter may change.
- This is used for modifying the values of actual parameters or
returning more than one value out of the function.
- This can be implemented by using addressof (&) operator before formal
parameters.