Class method access to it's data members

2019-09-06 00:21发布

问题:

I would use a small code to explain my question:

class C {
    int a;
public:
    func() {
        a = 4;
    };
};

int main() {
    C obj1;
    obj1.func();
    return 0;
}  

Here func() method tries to set a(a data member of obj1) to a value of 4. How does func() get access to a? Is it because func() has access to this* for obj1?
If that's true, how does func() get access to this*? Is it passed to func() as an implicit argument while calling obj1.func() from main()?
If it's passed as an argument, does main() stack consist of a this* stored as its local variable?
If no, how and when is the this* pointer generated and where is it stored?

I have tried to put across the question incrementally based on my understanding of the topic. If everything turns out to be true, I am confused whether for every object generated statically on the stack, an extra this* is stored on the stack.

Please feel free to suggest edits.

Thanks.

回答1:

For starters, let me answer your questions.

Here func() method tries to set a(a data member of obj1) to a value of 4. How does func() get access to 'a'? Is it because func() has access to this* for obj1?

Yes, your assumption is correct.

If that's true, how does func() get access to this*? Is it passed to func() as an implicit argument while calling obj1.func() from main?

I'll cover this more later in this reply, but yes. Every member function is passed an argument of self. The C++ compiler does this for you. Please note that static methods are an exception to this.

If it's passed as an argument, does main() stack consist of a this* stored as its local variable? If no, how and when is the this* pointer generated and where is it stored?

Take a look at the following examples. The first is in C and the second is in CPP.

struct A{
  int i;
}
increment(A* a){
 a->i +=1;
}

int main(){
  A anA; 
  anA.i = 0;
  increment(&anA);
}

Now, look at the following in cpp.

struct A{
   int i;

   public:
   void increment(){
     i+=1;
   }
}

int main(){
   A anA;
   anA.increment();
}

The examples above are, at a very basic nature, identical. They perform the same task and go about doing it in the same manner (excluding things like constructors/destructors). The main difference is that the cpp compiler takes care of passing a pointer to your model (struct A) to the function where in C you would need to pass it yourself.

this*, is really just a pointer to your struct. So in the example above its a pointer to anA.

I would suggest reading thinking in c++. It is free and one of the books that got me started with CPP. If you want to have a good understanding of the language its worth the time. here.