I have a question. I am trying to sere into my brain how pointers work and just when I think I got it a new problem arises. So I think I understand pointers pretty good when working with primitives and such. Now I am trying to understand working with objects and pointers.
So my problem is that if I write this:

int main()
{
objNumber *num1obj;


num1obj->setNum1(2);

num1obj->print();

delete num1obj;

return 0;
}

It compiles just fine but when I execute it, it crashes. My understanding is that this example is working on the Stack.
Now if I do this code:

int main()
{
objNumber *num1obj = new objNumber;


num1obj->setNum1(2);

num1obj->print();

delete num1obj;

return 0;
}

It compiles just fine as before, but now it returns the value I set in the parameter of setnum1(); and everything is flowers and sunshine in the world. My understanding is that since I added "new" I reserved a new space in memory on the Heap. If what I said about the Stack and Heap are true, why does it work on the Heap and not on the Stack. Or am I misunderstanding something here.

Thanks,

Dani

num1obj has not been initialized and is thus neither pointing on the stack nor on the heap - it is pointing nowhere at all. Therefore dereferencing it invokes undefined behavior.

Note that this is in no way specific to objects. If you dereferenced an int pointer that you did not initialize, it would cause the same problem.

"num1obj" is just a pointer of type "objNumber". A pointer is a special type of variable which can hold the address of an object. So by writing the line "objNumber* num1obj;", you have created a pointer variable in heap which can hold the address of an object of type "objNumber". Since you have not assign it with any valid address, it is pointing to some unallocated memory address. So in this case it is crashing to execute the line "num1obj->setNum1(2);".

The command "new objNumber" creates an object (in heap) of type "objNumber" and returns its address. So in the 2nd case the pointer is being initialized with a valid address of an object of type "objNumber", and hence it is working fine.

-
Amit M

So by writing the line "objNumber* num1obj;", you have created a pointer variable in heap

Like all local variables num1obj lives on the stack, not the heap.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.