Hello, cpp forum members and community. I am a new member and this will be my first post, of many, hopefully (and not all just about asking for advice, like this one).
Well to start with stating my problem: I am reading a book on C++, i am a beginner to the language and the world of programming entirely, but have been studying the book for about two months. So i feel i have a basic understanding of the syntax and how to use simple functions to make very basic programs.
One example in the book's chapter on functions and passing arguments to functions had only covered passing arguments by reference as opposed to passing by value and this is what i had been doing for just about every exercise that followed.
Example:
1 2 3 4 5 6 7 8 9 10 11
|
int someFn(int &variable)
{
variable += 1;
return variable;
}
int main()
{
int variable = 0;
someFn(variable);
/* variable is now = 1 */
}
|
Basic things like that. I believe I understand the concept of using the reference pointer in this situation. Today I looked in the chapter regarding classes and the author decides to go back into passing variables from main into functions using pointers and then states:
"Passing by reference is just another way of passing the address of the object.
C++ keeps track of the address of a reference, whereas you manipulate the
address in a pointer."
Here is the example code (not word for word, assuming that the book's source code is copyright):
1 2 3 4 5 6 7 8 9 10
|
int someFn(int* variable)
{
*variable = 10;
}
int main()
{
int variable = 1;
someFn(&variable);
/* 'Variable' is now = 10 */
}
|
I've used both of these techniques a few times and in a few different ways and still don't understand what the author was implying when he said "C++ keeps track of the address of a reference and manipulates the variable by using a pointer". To me they seem to perform the same operation. It seems a bit like: "You say tomato, I say tommatto." and I just wanted to be clear on this. I have a faint feeling I might just be over thinking it and that I am right in assuming he is saying its just another way to do the same thing.
That being said, I'd like to go ahead and cover all my bases on this so it doesn't come back to bite me later.
So, could someone please give me a few examples of where favoring one over the other might come in handy (if at all) and if it would,
why it would as well? :)