c++heap-memorymember-variablesstack-memory

How does ones code access member variables in a different stack frame


class foo {
  public:
    foo() : foo_member1(1)
    int foo_member1;
    void do_something() {foo_member1++;}
}

int main(){
    foo my_foo;
    my_foo.do_something();
}

Where is everything stored in the above example code? It was something I thought of whilst driving home and was embarrassed that I couldn't answer for certain. I create an object containing a variable both on the stack. When I call do_something and enter a new stack frame how does it have access to the member variable which was stored in the previous stack frame as part of the my_foo object? Is it copied in? Passed through silently underneath by reference? Or does it actually end up on the heap? Or is there some special mechanism by which code can access something that precedes it in the stack?


Solution

  • This:

       my_foo.do_something(); 
    

    Calls the method foo::do_something() by passing a hidden parameter this = &my_foo. This is just a regular C function that simply gets a hidden parameter. The code of do_something does not really access the stack frame of main, it simply uses this that main passed.

    Inside of do_something, the code is treated as:

    this->foo_member1++;
    

    No cross-frame access. It is just a pointer to a memory location, that happens to be in main's frame. There is no memory protection when passing pointers between functions.