0

Just a simple question.

the compiler gives me the option : virtual destructor, but I create a normal class without the virtual destructor

Is adding the word virtual before ~ the same as creating the class with a virtual destructor made by the compiler?

example

before:

~String();

after:

virtual ~String();

I am asking this question because I use other classes pointers inside of my "parent" class.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103

1 Answers1

0

Is adding the word virtual before ~ the same as creating the class with a virtual destructor made by the compiler?

No, it is not the same thing. Virtual destructors are useful when you have a parent and child class, and you want to delete an instance of the base class by first deleting the instance of the child class. This prevents a memory leak, which would have otherwise happenened if your destructor was not virtual; the base class instance would only have been deleted, leaving the derived instance to cause a memory leak.

See this example:

Parent *object = new Child();

// Do stuff

delete object;

If the child class destructor is virtual, then the memory alloted for the Child instance will be cleared first, and then the Parent instance will be cleared, ensuring that no memory leak take place.

If the Child destructor is not virtual, then the Parent instance will only be deleted, because object is an instance of Parent*. The Child instance will not be deleted, thus causing a memory leak.

Understanding the definition of virtual may be of use here:

...what the virtual keyword does is to allow a member of a derived class with the same name as one in the base class to be appropriately called from a pointer, and more precisely when the type of the pointer is a pointer to the base class that is pointing to an object of the derived class...

Sources:

Community
  • 1
  • 1
BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31