When to use virtual destructors

0 votes
I understand the majority of OOP theory, but virtual destructors are particularly perplexing.

I assumed that the destructor was called for every object in the chain, no matter what.

When and why should you make them virtual?
Jun 2, 2022 in C++ by Nicholas
• 7,760 points
592 views

1 answer to this question.

0 votes

When you want to delete an instance of a derived class using a pointer to the base class, virtual destructors come in handy:

class Base 
{
    // some virtual methods
};

class Derived : public Base
{
    ~Derived()
    {
        // Do some important cleanup
    }
};

You'll notice that I didn't make Base's destructor virtual in this case. 

Take a look at the following snippet now:

Base *b = new Derived();
// use b
delete b; // Here's the problem!

Delete b has undefined behaviour because Base's destructor is not virtual and b is a Base* pointing to a Derived object:

If the object to be deleted's static type is different from its dynamic type, the static type must be a base class of the object's dynamic type, and the static type must have a virtual destructor, or the behaviour is undefined.

In most implementations, the call to the destructor is resolved like any non-virtual code, which means that the base class's destructor is called but not the derived class's, resulting in a resource leak.

To summarise, whenever base classes are meant to be manipulated polymorphically, make their destructors virtual.

If you want to prevent an instance from being deleted through a base class pointer, make the base class destructor protected and nonvirtual; the compiler will not allow you to call delete on a base class pointer if you do so.

answered Jun 7, 2022 by Damon
• 4,960 points

Related Questions In C++

0 votes
0 answers

When and why do I need to use cin.ignore() in C++?

In C++, I developed a simple application that requested the user to enter a number and then a string.  Surprisingly, when I ran the application, it never paused to ask for the string.  It simply ignored it.  After conducting some research on StackOverflow, I discovered that I needed to include the following line: cin.ignore(256, '\n'); before the line with the string input  That addressed the problem and allowed the software to run.  My issue is why C++ need the cin.ignore() line, and how can I forecast when I will need to use it. Here's the software I created: #include <iostream> #include <string> using namespace std; int main() { ...READ MORE

Jul 4, 2022 in C++ by Nicholas
• 7,760 points
757 views
0 votes
0 answers

What is the difference between cout, cerr, clog of iostream header in c++? When to use which one?

I looked up the differences between cout, ...READ MORE

Jul 27, 2022 in C++ by Nicholas
• 7,760 points
718 views
0 votes
1 answer

What is a smart pointer and when should I use one?

A smart pointer is similar to a ...READ MORE

answered Jun 2, 2022 in C++ by Damon
• 4,960 points
477 views
0 votes
1 answer

How to pass in command line arguments when using ideone?

It appears that you won't be able ...READ MORE

answered Jun 21, 2022 in C++ by Damon
• 4,960 points
990 views
0 votes
1 answer

Why do we need virtual functions in C++?

A virtual function is a base class member function that we expect to redefine in derived classes. In the base class, a virtual function is used to ensure that the function is overridden.  This is especially true when a pointer from a base class points to an object from a derived class. For example, consider the code below: class Base ...READ MORE

answered May 27, 2022 in Others by Damon
• 4,960 points
1,220 views
0 votes
1 answer

Cases of static and dynamic binding in C++

When an object's static type is used to associate it with a member function, this is known as static binding (understand the type of its class). When a pointer or reference is associated with a member function based on the dynamic type of the object, this is known as dynamic binding (understand the instance of the variable at runtime). Before continuing, keep in mind that dynamic binding only works with pointers, references, and virtual functions for the base class. Because everything needed to call the function is known at compile time, the first call is a static binding (also known as early binding). Derived1 d1(1, 10); d1.display_data(); You already know that the d1 instance is a Derived1 automatic variable, and that it will call the Derived1::display data method (). The first condition is incorrect: d1 is neither a pointer nor a reference. The second condition isn't acceptable:  There is no virtual Derived1::display data. The second call is for ...READ MORE

answered Jun 7, 2022 in C++ by Damon
• 4,960 points
689 views
0 votes
1 answer

Are virtual functions the only way to achieve Runtime Polymorphism in C++?

fprintf is a polymorphism function in the C programming language. It can print to a file, stdout, a printer, a socket, or whatever else the system can represent as a stream if you supply it different handles. FILE* file = fopen("output.txt", "w"); ...READ MORE

answered Jun 21, 2022 in C++ by Damon
• 4,960 points
475 views
0 votes
1 answer

Why we actually need runtime polymorphism?

One of the most significant elements of ...READ MORE

answered Jun 10, 2022 in C++ by Damon
• 4,960 points
1,266 views
0 votes
1 answer

When to use extern in C++

This is useful when dealing with global variables.  Global variables are declared in a header so that any source file that contains the header is aware of them, but you only need to "define" them once in one of your source files. To explain, using extern int x; informs the compiler that an int object named x exists elsewhere.  It is not the compiler's responsibility to know where it exists; it just needs to know the type and name so that it may utilise it.  After compiling all of the source files, the linker will resolve all x references to the one definition found in one of the generated source files. For it to operate, the x variable's declaration must have "external linkage," which simply means that it must be defined outside of a function (at what's known as "the file scope") and without the static keyword. header: #ifndef HEADER_H #define HEADER_H // any source file that ...READ MORE

answered Jun 21, 2022 in C++ by Damon
• 4,960 points
2,356 views
0 votes
1 answer

How to use std::sort to sort an array in C++

We receive std::begin and std::end in C++0x/11, which are overloaded for arrays: #include <algorithm> int main(){ int v[2000]; ...READ MORE

answered Jun 1, 2022 in C++ by Damon
• 4,960 points
1,137 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP