C++ Programming - Constructors and Destructors - Discussion

Discussion Forum : Constructors and Destructors - General Questions (Q.No. 3)
Can a class have virtual destructor?
Answer: Option
No answer description is available. Let's discuss.
22 comments Page 1 of 3.

Tamal said:   4 weeks ago
Yes, a class can have a virtual destructor in C++.

When a class contains a virtual destructor, it means that the destructor can be overridden by a derived class. This is useful when we have a base class pointer pointing to a derived class object and we want to destroy the object through the base class pointer.

In this case, if the destructor is not virtual, only the base class destructor will be called, which may lead to memory leaks or undefined behaviour if the derived class has allocated some resources.

By making the destructor virtual, we can ensure that the destructor of the derived class is also called along with the base class destructor, which allows the derived class to release its resources before the object is destroyed.

Here's an example of a class with a virtual destructor:

class Base {
virtual ~Base() {
// Virtual destructor
class Derived : public Base {
~Derived() {
// Derived destructor
int main() {
Base* ptr = new Derived();
delete ptr; // Calls both Base and Derived destructors
return 0;

Siva darling said:   4 years ago
What is virtual destructor? please explain.

Ankit said:   5 years ago
Why is virtual constructor not possible? Please explain.

Amir Sandila said:   5 years ago
What is meant by virtual?

Gopika said:   5 years ago
What is meant by the term warping functions associated with virtual destructors?

Shikha Singh said:   6 years ago

No, because it doesn't make any sense in C++.

Virtual functions are invoked when you have a pointer/reference to an instance of a class.
Static functions aren't tied to a particular instance, they're tied to a class.

C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function virtually.

Amit said:   7 years ago
Virtual destructors are used to delete memory allocated for derived class. By default the destructor deletes memory just for base class.

Arun said:   7 years ago
What happens when a virtual function is declared as static?

Waseem Ahmad Naeem said:   8 years ago
If an object goes out of scope destructor is called automatically then why we need to call it explicitly?

Annonymous said:   8 years ago

Explicitly means we have to delete manually.

Post your comments here:

Your comments will be displayed after verification.