views:

124

answers:

2

In C++, what is the difference between:

 void func(MyType&); // declaration

 //...
 MyType * ptr;

 func(*ptr); // compiler doesnt give error

 func(ptr); // compiler gives error i thought & represents memory address so 
            // this statement should correct as ptr is only a pointer
            // or address of some real var.
+1  A: 

MyType& represents a /reference/, a completely different beast to pointers. If your function prototype were

func(MyType);

you would be working with a copy of the argument inside the function. With

func(MyType&);

you are working with the object itself (i.e., same object both in the calling and called scope). It is, for this case, like working with a pointer but using the same "dot" syntax as for objects.

Of course, this is a shallow and simplistic explanation. For me fulling grasping the deep zens below pointers, references, and the rest of the horde took years.

dignor.sign
+6  A: 

& in front of an object is the address-of operator, yielding the address of the object: &obj
& in front of an object that's about to be declared, is a type modifier, modifying the type of that object to be a reference: int &obj;

The same goes for *, BTW: In front of a pointer (or a pointer-like object, like an iterator), * is the dereferencing operator, yielding the object the pointer refers to: *ptr
* in front of an object that's about to be declared, however, is a type modifier, modifying the type to be a pointer: int *ptr

The fact that C and C++ don't care about the whitespaces around type modifiers and that this led to different camps when it comes to place them doesn't really make things easier. Some people place the type modifiers close to the type. They argue that it modifies the type and so it should go there:

int* ptr;

The disadvantage is that this becomes confusing when declaring several objects. This

int* a, b;

defines a to be a pointer to int, but b to be an int. Which is why some people prefer to write

int *ptr;
int *a, *b;

I suggest you shy away from declaring multiple objects in the same statement. IMO that makes code easier to read. Also, it leaves you free to pick either convention.

sbi
@sbi how about using typedef to int* in case of line 2 example ?
Kedar
@Kedar: Indeed, `typedef int* intptr; intptr a, b;` defines two `int*`. But my advice stays the same: One variable per declaration/definition.
sbi