in java we can do this:
public class A{
public static void main(String...str){
B b = new B();
b.doSomething(this); //How I do this in c++ ? the this self reference
}
}
public class B{
public void doSomething(A a){
//Importat stuff happen here
}
}
How can I do the same but in c++, I mean the self reference of A to use the method in B ?
First, in a static method there is no
thisparameter. Anyway, assuming that main() is not static here is how you can do it in C++In C++
thisis a pointer to the “current” Object. Thus if you definedoSomething()as taking a pointer to A (that is:doSomething(A* a)), then you will be able to receive thethisofA. The -> operator will give you access to the members of theaparameter, as follows:a->g().Alternatively you can pass
*thisand definedoSomething()to take a reference toA(that is:doSomething(A& a)):To access members of a reference you need to use the
.(dot) operator:a.g().