Passing by References versus raw pointers in C++. Const also covered

(Last Updated On: May 17, 2010)

Passing by References versus raw pointers in C++. Const also covered
References need to be initialized during declaration (i.e. int &i=10;) and they cannot contains values of null. They are an implicit pointer, they do not require dereferencing, no memory address required, and are safer then pointers.
Pointers offer advantages over references including they do not need to be initialized, program may need nulls so use pointers, and they can be stored in containers.

You should only initialize a reference within a non static member list so you should initialize references in constructors. It is also safer to pass by reference versus pointers. You should also pass by reference if there is expected large amount of memory being passed to functions.

Pre-pending an ampersande ( & ) makes a variable or object a reference. For example,
Int a;
Int b=&a;

Below is an example of passing by reference:
void swap( int & x, int & y )
int temp = x;
x = y;
y = temp;
int a=2, b=3;
swap( a, b );

No extra memory is needed so it makes passing by reference very efficient.

You should also use “const” reference arguments as well. Because of const, it will inadvertently protect your data that could get altered, passing without a const only enables you pass a non const only, and using const reference allows the function to generate temporary variables. This is a corrected example:

using namespace std;

double Cube( const double & num)
double result;
result = num * num * num;
return result;

int main() {
long temp = 4L;
double x = 3;
double value = Cube ( temp ); // long to double conversion
cout << "v= " << value << endl; return 0; }

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.


Check NEW site on stock forex and ETF analysis and automation

Scroll to Top