Search code examples
c++heap-memorynew-operatorscopes

How do you access variables that are allocated on the heap in C++ even after leaving the scope?


I'm having issues understanding the new keyword in C++. I understand that in order to not have memory popped off from stack after leaving scope; you can store it on heap. However in this example I get an error saying "identifier p is undefined"

#include <iostream>
#include <string>

class Person {
public: 
    int age; 
    std::string name;

    Person() {

    }

    Person(int a, std::string n): age(a), name(n){}
};


int main() {
    {
        Person* p = new Person(5, "bob");
    }

    std::cout << (*p).age; 

}

As you can see in my main function I've created another scope where I create a Person object on heap, from what I know the object will still exist after leaving the curly brackets, but then why is it not recognizing object p?

I've tried derefrencing p but the error remains the same. Any help would be great! Thanks


Solution

  • You are correct that the object still exists since you never deleted it. That is only half the issue though. The name p is local to the nested scope you declared it in. Once you exit that scope, p is destroyed and you can no longer access the object that you created.

    What you would need would be

    int main() 
    {
        Person* p;
        {
            p = new Person(5, "bob");
        }
    
        std::cout << (*p).age; 
    }
    

    and now you can access p since it was declared in main's scope.