I'm have a small confusion, and i need a little clarification; when you make something on the heap, like this:

int *somePointer = NULL;
somePointer = new int;

an int is created on the heap right?

This would be the equivalent of doing something like...:

int x;

...directly on the heap, right?

Also, what are the scope limitations of the heap? Any help?
~ Mike

I'm have a small confusion, and i need a little clarification; when you make something on the heap, like this:

int *somePointer = NULL;
somePointer = new int;

an int is created on the heap right?

This would be the equivalent of doing something like...:

int x;

...directly on the heap, right?

Right. But don't forget that heap memory needs to be deleted when you are done with it:

int *somePointer = new int;

*somePointer = GetInt();
cout << *somePointer << '\n';

delete somePointer;

Also, what are the scope limitations of the heap?

Scope limitations?

Ok, i got the first part, thanks :D

But as for scope, if i make an object on the heap, i can access it from anywhere right? It's like a global variable right?

But as for scope, if i make an object on the heap, i can access it from anywhere right? It's like a global variable right?

Heap memory is accessed through pointers. It's the pointer that has to follow scope rules, not the heap object. If you have a global pointer and point it to that address, it's like a global variable. If you have a local pointer and point it to that address, it's not like a global variable.

>This would be the equivalent of doing something like...:
No. In the first code, you declared a pointer which is pointing to a memory location. Hence, in this case you will be dealing with a pointer like interface. If the pointer was to object, you would refer to the member of the object as pointer->member rather than pointer.member
To get a variable like interface, you can use references as in:

#include<iostream>
int main()
{
    int* const ip=new int(5);// a const pointer
    int& i=*ip;// i is an alias to *ip
    
    std::cout<<i<<std::endl;
    i=6;// i behaves as if I declared it as int i
    std::cout<<i<<std::endl;
    delete &i;//the only difference is that I have to delete it
        
}

Regarding the scope of the dynamically allocated memory, the pointer will follow the scope rule. Everything will be same as statically defined object but the only difference will be that a dynamically defined object won't be self-destroyed once it become out of scope.

This article has been dead for over six months. Start a new discussion instead.