how to pass "this" in c++
c++
Solution
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).
Problem
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 } ```