简体   繁体   中英

How to use destructors on arrays of derived objects?

I have a three theoretical questions regarding virtual destructors: lets assume I have a base class Base - two derived classes Derivative_1 and Derivative_2 , class Stand_Alone and class Project . class Stand_Alone is used aa private member both in Base and Project . class Project has the private members: objects of Derivative_1 , a dynamic array of Derivative_2 objects and a Stand_Alone object. for the example lets assume that only one Project object is created in the main.

  1. is the destructor of Project correct - de-allocating all dynamic memory of an object?
  2. should the destructor of Base be declared as virtual ?
  3. the destructors of Derivative_1 and Derivative_2 shouldn't be declared as virtual , right?

thanks.

#ifndef PROJECT_H
#define PROJECT_H
#include "Stand_Alone.h"
#include "Derivative_1.h"
#include "Derivative_2.h"

class Project
{
public:
    Project();
    ~Project()
{
    delete [] support;
    support = NULL;
}
 protected:
 private:
    Stand_Alone member;
    Derivative_1 head;
    Derivative_2 *support;
};

#endif // PROJECT_H
  1. is the destructor of Project correct - de-allocating all dynamic memory of an object?

Yes, although there are safer ways of doing that. You could declare a vector of Derivative_2 objects instead of manipulating the memory yourself. This way you wouldn't need to declare a destructor at all, since the default destructor provided by your compiler would do the job pretty well.

  1. should the destructor of Base be declared as virtual ?

Yes, this is the only way to make sure that it will be called when objects of either its subclasses are destroyed.

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