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.
Project
correct - de-allocating all dynamic memory of an object? Base
be declared as virtual
? 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
- 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.
- should the destructor of
Base
be declared asvirtual
?
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.