this

closed account (jvqpDjzh)
//Hello! I was studying classes with out tutorials and I had a doubt...
//this is a pointer that is inside any non-static member function to refer to the internal status of the class...
But in the example below I can't really understand completely what that means, it's a bit ambiguous (for me at least) in the tutorial...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CVector& CVector::operator= (const CVector& param)
{
  x = param.x; 
  y = param.y;
  return *this;// 1)
}

// 1)
/* 
a) Is *this not a dereference of the pointer this?
a.1) Are we actually passing the object and not the pointer(?) => no, a reference! (?)

b) If we write "return this;",
it's the same thing of the return statement in the example? (if yes, why?)

c) We are returning an reference to the object of type CVector 
(from where this function is called) for what reason? 

If we apply the overloaded operator=, 
what does it mean? (see example below)
*/


//in the main.cpp
1
2
3
4
5
6
7
8
9
10

CVector v1;
CVector& vRef = &v1;//Is this correct?

//or:
/*
CVector& vRef = NULL;
vRef.operator=(&v1);
*/



Last edited on
to refer to the internal status of the class


no, not really. It is specific to the current object.

so with
 
return *this;


You are returning the current object, in this case allowing chaining so you could do something like this:

1
2

CVector myVector = someVector1 = someVector2 = someVector3;
Last edited on
closed account (jvqpDjzh)
With internal status I mean the data members (variables of the class). We can use this to refer to the data members:

1
2
3
4
5
6
7
class Foo
{
     int x;//data member

     Foo (int x) { this->x = x; }//using this to refer to a data member

};
Last edited on
closed account (jvqpDjzh)
Yes, that's what I supposed: with ' *this ' we are returning the current object (in this case this is used to do it), but in my example the function that overloads the operator ' = ' returns a reference and not an object! Why, if a function is supposed to return a reference, can return an object, we do it with: *this
Last edited on
Topic archived. No new replies allowed.