Destructors

B

Bushido Hacks

I need a little help with Destructors.
Suppose I created a multidimmensional array in a Base class that was
also accessable in a Derived class, would I need to delete the array
in the Derived class if I declared my destructors as virtual?

class Base
{
public:
...
virtual ~Base();
protected:
int m; // rows
int n; // cols
double** p;
};

class Derived : public Base
{
public:
...
virtual ~Derived();
};

Base::~Base()
{
for(int i = 0; i < m; i++){delete[] p;};
delete[] p;
};

Derived::~Derived(){
// Should these lines be here?
for(int i = 0; i < m; i++){delete[] p;};
delete[] p;
};
 
V

Victor Bazarov

Bushido said:
I need a little help with Destructors.
Suppose I created a multidimmensional array in a Base class that was
also accessable in a Derived class, would I need to delete the array
in the Derived class if I declared my destructors as virtual?

class Base
{
public:
...
virtual ~Base();
protected:
int m; // rows
int n; // cols
double** p;
};

class Derived : public Base
{
public:
...
virtual ~Derived();
};

Base::~Base()
{
for(int i = 0; i < m; i++){delete[] p;};
delete[] p;
};

Derived::~Derived(){
// Should these lines be here?
for(int i = 0; i < m; i++){delete[] p;};
delete[] p;


No, definitely not. The destructor for the base class will
take care of that.

The general rule -- the owner should take care of deleting
anything it owns.

V
 
J

James Kanze

Virtual or not doesn't change anything here.
class Base
{
public:
...
virtual ~Base();
protected:
int m; // rows
int n; // cols
double** p;
};
class Derived : public Base
{
public:
...
virtual ~Derived();
};
Base::~Base()
{
for(int i = 0; i < m; i++){delete[] p;};
delete[] p;
};
Derived::~Derived(){
// Should these lines be here?
for(int i = 0; i < m; i++){delete[] p;};
delete[] p;

No, definitely not. The destructor for the base class will
take care of that.

The general rule -- the owner should take care of deleting
anything it owns.

Just an idea, but I rather suspect that he simply wasn't
realizing that the derived class destructor always calls the
base destructor when it is finished, so he doesn't have to do
anything special with regards to the base class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top