C++ pointer question

Particle * createParticle() {
return new Particle;
}

void modifyParticle(Particle * p) {
p->x += 10;
}

Particle * p = createParticle();
modifyParticle(p);

I have a question while looking at this code.

  1. When receiving pointer p as a parameter in “modifyParticle”, and calling a function,

modifyParticle(p); I call it this way, and I wonder why in this function the parameter is not &p but just p.
If the parameter is a pointer, shouldn’t the parameter when calling the function be given an address value?

  1. Particle *p = create Particle(); the reason why I made the object a pointer is because the return type is the new Particle? And I know that if you use new, you can store it in the hip. Is p also stored in the hip?

I’m not sure if I’m a beginner. It’s complicated.

Hi Jewel,

I find it helpful to think of it this way; a pointer is a number, and that number is the address of the allocated space in memory for the object that you have created.

In order to clean up the object after you have finished with it, you should call “delete p”, which makes the memory available again. (You probably already know that if you don’t keep track of the objects you create and clean them up afterwards, you will likely get a memory leak.)

So to try to answer your questions :

  1. p is already a pointer, when you create the particle object using “new Particle()” memory is allocated for the object and the address of that memory is stored in p. It’s literally a number that is the memory address.

If you were to use &p you would be getting the address of the pointer itself, not the number stored in p (which is the address of the memory allocated to the particle object).

2… actually I must admit I’m not sure what you mean by hip in this context…? But calling new Particle() will allocate memory for the object, it’s not on the stack.

Hope this helps!

Seb

Hi,
adding to what @seb_ly mentions, I think you mean “heap” and not “hip”. Yes, whenever you use new it will be allocated in the heap.

But then, I would recommend you to avoid at all cost using the new keyword, as it requires you to take care of deleting and if not done properly can lead to memory leaks or your app crashing. When you come from Java or Javascript for example, this does not happen and you need to use the new keyword. But in C++, it is not recommended. If you really need to use a pointer instead of a regular instance you should use an std::unique_ptr or std::shared_ptr. Other wise just use a regular instance.

Thus, don’t make a createParticle() function. you can simply use the Particle class constructor.

//notice that there is an & in the function parameter. This means that you are passing a reference.
void modifyParticle(Particle & p){
p.x += 10;
}

Particle p; // this creates a regular instance of Particle class
modifyParticle(p);

hope this helps.

if you post your full code it could be easier to give you a hand.

1 Like