Reputation: 11
When I write the code to allocate memory on the free store in c++ i was curious about assigning a pointer to that data . for example:
as i declare and initialize a pointer like so,
unsigned short int * pPointer = new unsigned short int;
*pPointer = value;
delete pPointer;
is 4 bytes; using the new keyword allocates on the free store and I can assign a value to that address . But my question is, why do I need to reestablish it's type in order to assign my pointer?
I want to do:
unsigned short int * pPointer = new pPointer
easy?
Javascript would use a method
newMethod = new Method()
to access member data in the method .
But i get how a pointer is used .
pPointer = member data address and *pPointer = member data value
and everytime I try something like ,
int * pLocal = &pPointer
throws an error . cannot convert int** to int* is trying to reserve the same memory space which is why I cannot store its address in another pointer its just reserved memory .
sorry if this is confusing but i just wanted to know how to allocate memory on the free store and accessing it using a pointer already has a type with a sizeof() memory default needs another type declaration after the new keyword ?
Upvotes: 0
Views: 883
Reputation: 96810
But my question is, why do I need to reestablish it's type in order to assign my pointer?
When you're allocating with new
you need to provide the type. This is because the compiler doesn't know what you're allocating and it needs the type in order to establish the correct allocation strategy for that specific type given certain information (i.e how many bytes is the type, alignment, etc).
Note that the type won't always be the same as the pointer. For example, if you have a base class B
and a derived class D
, you can assign a base class pointer to the address of a derived class instance (i.e B* ptr = new D
).
Javascript would use a method
newMethod = new Method()
JavaScript doesn't have pointers, and new
doesn't work the same way in that language. It simply creates a new instance of the given class (function).
Upvotes: 1