-6

In C you have to free the memory that has been allocated by the program. Does the same go for objects in C++?

class Common
{
    //some function declarations
}

void example()  
{
    Common obj;
    //do stuff with obj
    delete obj;
}

How important is delete obj; here if i asume the function example() will be called once only?

  • You do not, actually you **should not** `delete` anything on the stack. That is only if you `new` the object. The variable's memory will be freed as soon as the variable falls out of scope, at the end of your `example` function in this case. – Cory Kramer Oct 08 '14 at 20:02
  • Your first sentence is not entirely correct. – juanchopanza Oct 08 '14 at 20:02
  • This applies only to dynamically allocated memory. – c0dehunter Oct 08 '14 at 20:03

1 Answers1

1

You have not to delete a local object of a function that is allocated on the stack. You have to delete objects that were allocated using the operator new.

Moreover, the delete operator is applied to pointers. Your code snippet will not compile.

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335