Re: Pointer to class example
Pointers just store the address of a variable, the variable itself can be allocated on the heap or on the stack (if it's allocated on the heap you need to call delete on the pointer to free the allocated memory).
In your case you have the object a and it's allocated on the stack, and the pointer c holds its address, this happens at the line: c = &a;
LE: the cases with new and delete are the cases where pointers hold the address of a variable on the heap (this variable doesn't have a name, but it is there and you can only use it with the help of the pointer that holds it's address.
Example, this line:
Code:
int *ptr = new int(21);
Will create two variables: one pointer to integer and one integer (with value 21) and the integer variable can only be accessed using the ptr pointer.
For heap variables you need to call delete, like this:
If you don't call delete and the ptr pointer gets out of scope, you will have a memory leak (you have allocated memory that you can't access to delete it)
Re: Pointer to class example
Quote:
Originally Posted by
loves_oi
[code]
there are two pointers : b and c.We allocate memory for b , but not for c.Why ??Doesn't it make difference??
Why? because b points to somewhere that has an object (a on the stack).
You just need to remember that pointers are only useful if they point to somewhere useful. 'Useful' is normally an object, but can be functions/member functions as well.
b is set to point at an object on the stack (a), c is set to point at an object on the heap (c)
Re: Pointer to class example
I grasp the general picture,thanks for that.But still I have some questions...What happens in the memory during processes?I will say what i understood.please correct my mistakes if available.
after the declaration:
Code:
CRectangle a, *b, *c;
Firstly(for a),an object of class CRectangle is created .(memory allocated on stack)
Secondly(for *b),a pointer to an object of CRectangle class is created(memory allocated on stack).In other words , a virtual box is created in the memory and an address number will come into the box.
With ,
an object of class CRectangle is created(memory allocated on heap) and the address of that object is given to the virtual box B.Therefore b points to that object;
Thirdly(for *c),again a pointer to an object of CRectangle class is created(memory allocated on stack).In other words , a virtual box is created in the memory and an address number will come into the box.And then with,
the addres of a is given to the virtual box C.Therefore,c points to a.