简体   繁体   中英

C++ : What is the Right way to delete a derived class instance?

Assuming we have :

class A {
protected:
    int* iArr;
    float *fArr;
public:
    A(int* iArr,float *fArr);
    ~A();
}

class B : public A {
private:
    double *dArr;
public:
    B(int* iArr,float *fArr,double *dArr);
    ~B();
}

my intuation was that it would only invoke B's destructor but when i ran it on Visual C++ i saw that when destructing an instance of B it calls both A and then B destructor.

What is the correct way to write destructor in a derived class then? do i always need to assume parent class would take care of deleting everything but what only the derived class have?

Edit :

  1. if it is so, then what if the child extending parent class only with overriding functions,does that mean that i leave the child's destructor empty?

  2. what if i want to change that? i mean what if i want only child destructor to be called? is there a way to do that?

In a word, yes.

The parent class's destructor always gets called automatically. Its job is to free up all resources used by the parent class.

The child class's destructor is responsible for freeing up things that are specific to the child class.

Additionally, if you ever delete instances of the child class through a pointer to the parent class, you need to make the parent class's destructor virtual. See When to use virtual destructors?

The destructor of A should be virtual. Your problem lies that if you do the following:

A* b = new B( iArr, fArr, dArr );
delete b;

Then B's destructor won't get called because b while being instantiated as a B looks like an A and B's destructor doesn't have an entry in the virtual table which means it doesn't know its there (ie it thinks its just an A)

Edit:

In answer to 1 you could leave the destructor empty or you could not define it.

In answer to 2, you can't really do that. You'd be best off having a virtual protected function called "Destroy" or something thats called from the base class destructor. That is the only way I can think of to control destruction like you describe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM