-1
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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • The terms _stack_ and _heap_ are pretty much undefined regarding c++. Better refer to _local_ and _dynamic_ allocation. – πάντα ῥεῖ Mar 17 '19 at 20:00
  • The basic answer is that you shouldn't care at this layer of abstraction. It's up to the compiler and linker to make it all work for a target platform. Read up on https://en.wikipedia.org/wiki/Calling_convention – Ahmed Masud Mar 17 '19 at 20:06

1 Answers1

0

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.

Michael Veksler
  • 8,217
  • 1
  • 20
  • 33