Search code examples
c++virtual-destructor

I have a virtual destructor and an array in my base class. How can I make it work?


Ex:

class base
{
public:
  base()
  {
    // allocate memory for basearray
  }
  virtual ~base()
  {
    // delete basearray
  }

protected:
  float* basearray;
};

class derived1 : public base
{
public:
  derived1()
  {
    // allocate memory for derivedarray
  }
  ~derived1()
  {
    // delete derived array
  }

protect:
  float* derivedarray;
};

void main()
{
  derived1 d;

  ...

  base* pb = &d;

  ...

  // Delete base array? 
}

I have a virtual destructor and an array in my base class. If the base class destructor is overridden by the derived class destructor, then the basearray won't get deleted. What's a nice solution?


Solution

  • The base-class destructor is automatically called, right after the derived-class destructor has run.