It has been a while since I read function calls in C++ so everything that I write might not be 100% accurate but you will get the general idea.
In C++ parameters are passed to functions by value. What this means is that when you have a code like this
void someF(int someCount); // function declaration body is defined somewhere else in the code
void someF(int someCount); // function declaration body is defined somewhere else in the code
To copy to clipboard, switch view to plain text mode
And you make a call to someF by
someF(someNumber);
someF(someNumber);
To copy to clipboard, switch view to plain text mode
What basically happens is that someNumber is put on the stack function someF is called and then someCount is initialized by copying the value from the stack. This is both time and memory consuming. Second any change on someCount won't be transferred to someNumber.
Using reference as a function parameter is similar to using a pointer but less error prone. You only pass a object address to the function which is faster and uses less memory. Only the address of the object is put on stack and copied. Also changes are transferred to the original object that you used to initializes the function parameter.
Now if someF is declared as follow
void someF(int &someCount); // function declaration body is defined somewhere else in the code
void someF(int &someCount); // function declaration body is defined somewhere else in the code
To copy to clipboard, switch view to plain text mode
You can use only int type to initialze the parameter. If you have const int that object can't be used because theoretically inside the function you can change the value of the object you passed as the parameter. In functions that don't change the value of the parameter being passed to them it is wise to use const reference as a parameter because you can pass both const and non const objects and if somewhere you try to change the value of the passed parameter it will generate a compiler time error.
To conclude. Const reference is not a must but it is wise programing practice. You should try to understand and accept this coding practicies because they help you write better code, and make debugging easier.
I hope I clarified the problem for you. If I wasn't clear enough, my english is not that great, tell me and I will try to explain better.
Bookmarks