C++ Programming - Constructors and Destructors - Discussion

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

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;
}
(2)

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

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

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

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

Shikha Singh said:   8 years ago
@Arun

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:   8 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:   9 years ago
What happens when a virtual function is declared as static?

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

Annonymous said:   10 years ago
@Abc.

Explicitly means we have to delete manually.


Post your comments here:

Your comments will be displayed after verification.