Edit: using some kind of smart pointer is often a good idea, but I find it still important to have a clear understanding of manual memory management in C ++.
If you want the object in the class to remain until the end of the program, you can simply make it a member variable. From what you said, there is nothing to suggest you use new
or delete
here, just make it automatic. If you want to use new
and delete
for practice, you should read the constructors and destructors for the class (you can and will use new
and delete
outside the classes, but I'm trying to save this according to your question). Here I prepared earlier:
class Foo { public: Foo();
This is a simple example, but it will hopefully help you. Please note that the variable will be saved only as long as the object is alive. If the object is destroyed or goes out of scope, the destructor will be called and the memory will be freed.
source share