Alon Shmiel
Alon Shmiel

Reputation: 7121

Implement a destructor

I have a class: A and I wrote the destructor.

now I have a class B:

class B {
    A* a;
  public:
    B() {
      a = new A[10];
    }

    ~B() {

    }

};

I want to implement the destructor of B.

I think something like:

~B() {
  delete[] a;
}

but I got an error.

maybe I have to do the next line?

delete a;

any help appreciated!

Upvotes: 2

Views: 492

Answers (1)

NPE
NPE

Reputation: 500157

You don't say what error you got, but the following compiles without errors:

class A {};

class B {
    A* a;
  public:
    B() {
      a = new A[10];
    }

    ~B() {
      delete[] a;
    }
};

Note that this is incomplete in that it violates the Rule of Three. B::a should either be a suitable smart pointer, or the class needs to implement a copy constructor and a copy assignment operator (or disable both). An even better option is to use std::vector or std::array instead of the raw pointer.

Upvotes: 4

Related Questions