0

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.

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • 3
    contrary to common belief memory is managed automatically in c++ (unless you explicitly ask for something else) – 463035818_is_not_an_ai Nov 21 '19 at 09:04
  • 1
    I would recommend obtaining one of [these books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) if you want to learn C++. You won't get far by piecing your knowledge together from documentation articles. – Max Langhof Nov 21 '19 at 09:16

2 Answers2

2

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);
Blaze
  • 16,736
  • 2
  • 25
  • 44
  • As I said being completely new to c++ and memory management in it. Does the first not result in allocated memory that is not deallocated until the program finishes? – SomeDutchGuy Nov 21 '19 at 09:04
  • 2
    In the first one, the memory is on the stack and will be invalidated like any other stack variable. Just like how for instance `int a;` would become invalid after the block it was declared in. – Blaze Nov 21 '19 at 09:06
0

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.

Pickle Rick
  • 808
  • 3
  • 6