Search code examples
c++classdatamember

Where is local variable of member function created if object is created via new?


Class A
{
    int a;
    int get_a()
    {
       int d;
       return a;
    }
};

A* obj_a_ptr = new A;
int c = A->get_a();

Where is int d memory allocated , in heap or stack ?


Solution

  • Member functions are not that different from free functions, they only implicitly get a this pointer as first parameter. So your member function is more or less equivalent to (lets forget about the fact that nothing in your A is actually accesible, because it is all private)

    int get_a(A* obj)
    {
       int d;
       return obj->a;
    }
    

    I hope this already answers your question. Whether obj was allocated via new or not makes no difference for d being on the stack.