MyClass* and MyClass&

Hello.
Let's consider the following code:
1
2
  void myFuncion(MyClass* foo);
  void myFuncion(MyClass& foo);

Could you tell me if I am right?, since I am having troubles with pointers.
The first one it says foo is a pointer to MyClass.
The second one it says foo is an instance to MyClass passed by reference.
Both functions can modify the attibutes of foo, none of them make a copy of foo and the only difference is that I'd have to write foo->myValue and foo.myValue, respectly.
Am I right or am I missing any detail?

Finally, is it all the following exactly the same (just moving &)?
1
2
3
  void myFuncion(MyClass& foo);
  void myFuncion(MyClass & foo);
  void myFuncion(MyClass &foo);


Thank you again.
The first one it says foo is a pointer to MyClass.

foo is a pointer to a MyClass object (also called an instance). I guess that is what you meant but just to make sure..

The second one it says foo is an instance to MyClass passed by reference.

foo is not an instance. foo is a reference to a MyClass object/instance. It's the object that you pass to the function that is passed by reference.
1
2
3
4
MyClass bar;
myFuncion(bar); // bar is passed to the function by reference.
                // During this call to myFuncion foo will refer to bar, so any 
                // changes made to foo inside the function will modify bar. 


Both functions can modify the attibutes of foo

Both can modify the object that foo refers/points to.

none of them make a copy of foo

The pointer that is passed to the first function is copied but the object that the pointer points to is not copied. In the second function the argument is not copied unless the function do so explicitly inside the function.

the only difference is that I'd have to write foo->myValue and foo.myValue, respectly.

More or less yes, but note that a pointer can be null (meaning it doesn't point to any particular object) so if you want the function to be able to handle that case you will have to make sure the pointer is not null before you start using it. A reference can never be null.

Finally, is it all the following exactly the same (just moving &)?

Yes they are the same. It's just a matter of personal preference. Personally I prefer the first one.
Last edited on
Reference is an additional name for a variable.

Pointer is a variable that can store an address of a variable. Pointer can hold a null, i.e. point to no variable.


Last one: amount of whitespace makes no difference.
Thank you a lot. My doubts were solved.
Topic archived. No new replies allowed.