Difference between reference and pointer?

What is difference between reference and pointer or pass by reference and pass by pointer?

Questions by janhavibend   answers by janhavibend

Showing Answers 1 - 5 of 5 Answers

rocky2583

  • Jul 20th, 2008
 

In C there is no concept of a reference variable.
Only pointers exist. When you pass address of any variable to a function, it is termed as pass by reference. Coz the formal parameter in function is the pointer that stores this address.

In C++, reference variables exist. A reference variable does not get any memory of its own. It must be initailzed when it is declared and it acts as an alias or synonym for the variable which was used to initialze it.

There are two ways to pass the variable by reference in C++

1) Traditional pass by reference approach.
someFunction (&a, &b);

void someFunction (int *x, int *y)
{
}


2)
someFunction (a, b);

void someFunction (int &x, int &y)
{
}

In this case no memory is allocated to x & y.
They act as alias for the memory locations to which a & b are referring.
any changes made to the values of x & y will cause values of a & b in the calling function to change respectively.

Both approaches 1) and 2) are called pass by reference. But first approach uses pointers and second approach uses reference variables.

prkgroup

  • Sep 28th, 2008
 

Reference is any variable address represent '&' with front. But pointer is a variable. Which reference another variable. Reference variable holds value. Which is not a address.

  Was this answer useful?  Yes

mail2kul

  • Jun 8th, 2009
 

C++ supports passing an object  by reference and pointer, former is widely used in the C++ where as C doesnot support passing user defined data by reference.

Consider the following example

Employee *ptr; // is a placeholder
Employee &ref; // compiler throws error

Pointer may point to variable or not at any given point in time. We can define pointer without having any data in hand. later we can make it to point to some data of defined type.
Reference can't be defined as pointer. to define reference we need to have data already available, failing to do so generates compiler errror.

Above statments can be made working as
Employee &ref = manger; // manager is already created object.


  Was this answer useful?  Yes

abhimanipal

  • Jan 15th, 2010
 

Is there any advantage of using a reference variable as opposed to using a pointer. I mean pass by reference ( by using pointers ) was implemented in C. Why is this new technique of pass by reference (using reference variable ) invented for C++

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Answer Question

Click here to Login / Register your free account


 
Send   Reset

 

Related Answered Questions

 

Related Open Questions