0

I'm learning about destructors a bit, and wanted to see if this is the right way to write them externally as opposed to inside the Class.

class Foo
{
private:
    int* array;
    int arraySize;
public:
    Foo(int size)   // Assume "size" is > 0
    {
        arraySize = size;
        array = new int[size];
    }

    ~Foo();
};
Foo::~Foo() {
    delete array;
    delete &arraySize;
}
jacksonSD
  • 677
  • 2
  • 13
  • 27
  • 1) Why are you deleting `arraySize`? 2) You are using the wrong form of `delete`. It should be `delete[] array;` – PaulMcKenzie Apr 28 '14 at 00:49
  • @PaulMcKenzie like I said, just reading up on it. The example I saw showed the destructor deleting all the data members in the class so I wasn't sure. Thanks for the tip on delete[], appreciate it – jacksonSD Apr 28 '14 at 00:53
  • The example is wrong. You can only `delete` a pointer value that points to the beginning of a dynamically allocated block of memory created with `new`. – PaulMcKenzie Apr 28 '14 at 00:55

1 Answers1

0

Defining a destructor outside the class definition is no difference from defining a normal function outside the class definition:

return_type class_name::function_name(..)
{
   ...
}

except that there is no return_type for destructor(and constructor).

By the way, the way you use delete is wrong. You should only delete objects that you previously allocated on heap by new. And deleting an array is different from deleting a single element, as you need specify explicitly.

Foo::~Foo() {
    delete array;      // should use delete [] to delete an array on heap
    delete &arraySize; // don't delete an object on stack, cos it's not "newed"
}
Eric Z
  • 14,327
  • 7
  • 45
  • 69