Monday, July 02, 2007

References and Pointers are Same in C++?

.

.

.

Ans :-



No, they are not.It is important to realize that references and pointers are quite different.



S.No

Pointers

References

1

creating a pointer creates a new object.

creating a reference does not create a new object; it merely creates an alternative name for an existing object.

2

A pointer should be thought of as a separate object with its own distinct set of operations (*p, p->blah, and so on).

the operations and semantics for the reference are defined by the referent; references do not have operations of their own.

In the following example, notice that assigning 0 to the reference j is very different than assigning 0 to the pointer p (the 0 pointer is the same as the NULL pointer; see FAQ 1.09).

int main()

{

int i = 5;

int& j = i; <-- 1

int* p = &i; <-- 2


j = 0; <-- 3

p = 0; <-- 4

}

(1) j is an alias for i

(2) p is a new object, not an alias

(3) Changes i

(4) Changes p; does not affect i



No comments: