Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass "this" in c++

Tags:

I'm confused with the this keyword in C++, I'm not sure that if I'm doing the right thing by passing this. Here is the piece of code that I'm struggling with:

ClassA::ClassA( ClassB &b) {      b.doSth(this);     // trying to call b's routine by passing a pointer to itself, should I use "this"? }  ClassB::doSth(ClassA * a) {        //do sth } 
like image 353
cplusplusNewbie Avatar asked Dec 01 '09 03:12

cplusplusNewbie


People also ask

How do you pass by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

How do you pass this pointer in C++?

Passing Pointers to Functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

Does pass by reference exist in C?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

Why do we pass by reference?

If you recall, using pass by reference allows us to effectively “pass” the reference of a variable in the calling function to whatever is in the function being called. The called function gets the ability to modify the value of the argument by passing in its reference.


2 Answers

You're using it correctly. The this pointer points to the current object instance.

class helper  { public:      void help(worker *pWorker) {           //TODO do something with pWorker . . .      }       void help2(worker& rWorker) {           //TODO do something with rWorker . . .      } };  class worker  { public:      void dowork() {           //this one takes a worker pointer so we can use the this pointer.           helper.help(this);            //to pass by reference, you need to dereference the this pointer.           helper.help2(*this);      }      helper helper; }; 

Also, say you declare worker *pW = new worker(). If you call one of the methods (dowork) on the pW object, you will notice that the this pointer and pW have the exact same value (they are both the same address).

(haven't tested that to make sure it builds, but I think it should).

like image 167
cchampion Avatar answered Nov 12 '22 13:11

cchampion


In C++, this is a keyword which is defined as "the pointer to the current object instance". So your code above is correct.

Depending on the inheritance/composition relationship between ClassA and ClassB, there are probably better ways to achieve what you are doing than by using the this pointer.

like image 42
LeopardSkinPillBoxHat Avatar answered Nov 12 '22 15:11

LeopardSkinPillBoxHat