SecretIndividual
SecretIndividual

Reputation: 2519

Removing objects from memory in c++

I am new to c++ but from what I understood you need to delete objects from memory when you are done with them.

Having a class called myClass. If I create a new instance and call some of its functionalities. Like so:

MyClass p;
p.funcCall(12);
p.anOtherFuncCall(4);

How am I supposed to free the memory occupied by p again? I read this Microsoft article. But if I change it to:

MyClass* p = new MyClass
... call fucntions
delete p;

I can no longer call my functions like p.funcCall(12).

If I understood memory management in c++ incorrectly I would love to hear that as well.

Upvotes: 0

Views: 244

Answers (2)

Pickle Rick
Pickle Rick

Reputation: 808

So basically C++ won't manage memory for you, at least it's not a default feature of the language. That certainly doesn't mean that you need to store every object as a pointer and free it manually though. In your case the object is initialized in the local scope which means it will get destroyed as soon as it leaves that scope. This is because you constructed it as a value, if you had allocated memory yourself for it (i.e global scope) then you're responsible for freeing said memory. There's another option for pointers as well though, using smart pointers will automate the cleanup of objects in the global scope.

Upvotes: 0

Blaze
Blaze

Reputation: 16876

In this code

MyClass p;
p.funcCall(12);
p.anOtherFuncCall(4);

You don't have to manually delete p. It is automatically invalidated once it goes out of scope. This is explained in greater detail here. You can just leave it this way.

MyClass* p = new MyClass
... call fucntions
delete p;

You can also do it that way if you want. Since p is not a MyClass anymore but a pointer to one, the syntax is different, though. You have to write it like this instead:

p->funcCall(12);

Upvotes: 2

Related Questions