C++ Programming - Constructors and Destructors - Discussion
Discussion Forum : Constructors and Destructors - General Questions (Q.No. 3)
3.
Can a class have virtual destructor?
Discussion:
22 comments Page 3 of 3.
Siva darling said:
6 years ago
What is virtual destructor? please explain.
Tamal said:
2 years 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 {
public:
virtual ~Base() {
// Virtual destructor
}
};
class Derived : public Base {
public:
~Derived() {
// Derived destructor
}
};
int main() {
Base* ptr = new Derived();
delete ptr; // Calls both Base and Derived destructors
return 0;
}
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 {
public:
virtual ~Base() {
// Virtual destructor
}
};
class Derived : public Base {
public:
~Derived() {
// Derived destructor
}
};
int main() {
Base* ptr = new Derived();
delete ptr; // Calls both Base and Derived destructors
return 0;
}
(2)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers