1. Why is there '&' symbol in this parameter?? CVector operator+ (const CVector& first, const CVector& second)
or this one also bool Dummy :: isitme(Dummy& isme)
2. Actually, I dont really understand what is "this" keyword is.
like in this code :
& means pass by reference. If you do that, and the routine changes the variable, the variable it was called with is ALSO changed, since it is an 'alias' for the input. So the const stops you from changing it -- some routines change on purpose as a form of returning the result. When its used with const, its done just to avoid copying the original into a new variable, which takes a lot of time for classes and containers.
this means the one that belongs to the class.
here, in your example, EDIT … its check to see if itself was passed in by using the address. So if you had a reference or a pointer to something and the original, you can see if they are the same thing. Which seems kind of messed up to me …
this ^^ as above is a pointer. *this dereferences it. that is, in this example, this has a type of Cvector* but the routine returns a Cvector, not a pointer to one, so you have to dereference it.
int x = 42;
int y = 42;
// x == y, they are equal
// &x != &y, x and y are not the same object
Context. The & in OP question is part of type declarator.
There are other contexts.
1 2 3 4 5 6 7 8 9
void function( T & par ) // par is a reference to object of type T
{
int var = 7;
int& ref = var; // ref is a reference to object of type int
int* ptr = &var; // * means that ptr is a pointer
// & is address-of operator
std::cout << * ptr; // * is dereferencing operator
std::cout << (var * par); // * is binary operator*, (multiply?)
}
Every member function has implict pointer (this) to the object that calls the function.
Without implicit this:
1 2 3 4 5 6 7 8 9 10 11 12 13
struct T {
// code
};
T& function( T* object, int x ) {
// code
return *object;
}
int main() {
T foo, bar;
bar = function( &foo, 42 );
}
C++ as it is:
1 2 3 4 5 6 7 8 9 10 11 12
struct T {
// code
T& function( int x ) {
// code
return *this;
}
};
int main() {
T foo, bar;
bar = foo.function( 42 );
}