The main thing to know here is about copy constructor and references. Learn that quick if you want to improve your programming skills.
Example with builtin type (int, float, ...):
- int i = 0;
-
int j = i;
-
-
i = 2;
-
ASSERT(j == 0); //is true
j is a copy of i at a given time. So changing i doesn't affect j;
But, if i had a reference on i, thinkgs would have been different:
- int i = 0;
-
int & j = i; //here j is a reference on i
-
-
i = 2;
-
ASSERT(j == 2); //is true
This is the same thing for complex object like class or struct. The reasons we use them more on complex object its because that prevent a copy construct called which is totally unefficient.
- string s = "a very long and very big string ...";
-
-
string s2 = s; //s2 is a copy so the whole string was copied
so using function like this:
- void f(string s);
-
f(s); // you have a copy passed as an argument, this is slow
But:
- void f(string const &s);
-
f(s); // very quick parameters passing. The const is used to tell the compiler that s is supposed to be unmodified in f.
because:
- void f(string &s);
-
f(s); //quick but my string s could be totally damaged in f!
So references act like pointers, but they are more elegant and intuitive to use because if you used a reference you do not have to test if it is null or not. Compiler garanty that it can't be null, though it can reference a deleted object, but that's another story.
Also about "this". this is the pointer on the class object your in. "this" refers to your current object in a given class method. So "*this" means the class object derefenrenced. So you can return yourself either as a copy (slow) or as a reference (quick) either const or not.