how to pass "this" in c++

Viewed 46690

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
}
7 Answers

If what you want is to make it the this as in thiscall, or, the actual very first parameter of any member functions (for g++), there is only one way: by the member access operators:

A* a = sth_that_give_you_an_A();
((B*)a)->doSth();

or in your case, if you want to pass the instance of class A to B::doSth.

((B*)this)->doSth();

Or, you may want to cast it to void* first to make your compiler happy. If this is what you actually want, it is somehow the only way to do that.

However, an instance of class A may not also be an instance of class B. It is very rare that you want actually do this. You should find a proper way that allow you to down cast an instance of A to its subclass B with confidence.

Or otherwise, if you want to call B::doSth on the instance of B, it is just as normal as what you may do.

Related