I began learning c++ about two weeks ago with the online tutorial on cplusplus.com, which seems overall to be the best tutorial I've come across. I have been using NetBeans 6.9 on Lubuntu linux, which in my opinion, greatly enhances learning because of it's code assistance feature, general organization of projects and it's automatic creation and maintenance of makefiles. When you compile a program it will actually change the #include's to include only the ones you need, which is amazing.
On page 98 of the tutorial, under 'keyword this' it says:
int isitme (CDummy& param);
Since the tutorial doesn't cover placing the ampersand after an object, I was wondering if someone could translate this to english for me. I have found it only in the declaration/implementation of an object, like this constructor:
const type &bar declares a reference that can't modify the object it's referencing, it's used in order not to copy large objects when passing them to some function
void FuncByValue( int n )
{
n = 1;
}
void FuncByRef( int& n ) // Example of 1.
{
n = 2;
}
void FuncByPtr( int *n )
{
*n = 3;
}
int main()
{
int i=5;
FuncByValue( i ); // The value assigned inside the function does not affect i after it returns
cout << i << endl;
// In the following 2 function calls, i is modified when the function returns.
FuncByRef( i ); // same as pointer but compiler automatically takes address for you.
cout << i << endl;
FuncByPtr( &i ); // Example of 2.
cout << i << endl;
}
There are many opinions on that, I personally prefer int &a; because if you write int& a, b; b will look like a reference but it's not, int &a, b; makes it clearer
Pointers and references accomplish the same thing.
So why did they add references to C++?
One reason is a pointer does not have to be initialized when declared, whereas a reference does. (A common bug in C is using uninitialized pointers, which usually leads to a crash)
In the previous post the following line will cause a complie error.