Write a program where the destructors should be virtual. Explain.

What will be an ideal response?


The requested code and further discussion follow.
```
#include
using namespace std;
class B
{
public:
B():bPtr( new int[5]){ cout << "allocates 5 ints\n"; }
virtual ~B()
{ delete[] bPtr; cout << "deallocates 5 ints\n"; }
private:
int * bPtr;
};

class D:public B
{
public:
D():B(),dPtr(new int[1000]){cout << "allocates 1000 ints\n";}
~D() { delete[] dPtr; cout << "deallocates 1000 ints\n"; }
private:
int * dPtr;
};
int main()
{
for (int i = 0; i < 100; i++)
{
B* bPtr = new D;
delete bPtr;
}
cout << "\nWithout virtual destructor, \n";
cout << "100 * 1000 + 500 ints allocated\n"
<< "but only 500 ints deallocated.\n";
cout << "\nWith virtual destructor, \n";
cout << "100 * 1000 + 500 ints allocated, and "
<< "100 * 1000 + 500 ints deallocated.\n";
}
```

In this code, if the base class destructor is not virtual, the system must bind the pointer to the destructor at compile time. The pointer in main, bPtr, is of type B*, i.e., pointer to B, so it is bound to B’s member functions. The destructor for D, ~D fails to run.
If the keyword virtual is removed from the destructor in the base class, class B, the derived class destructor ~D is not called. Approximately 400K of memory would then be leaked.

Computer Science & Information Technology

You might also like to view...

A(n) __________ can be thought of as a blueprint that can be used to create a type of __________.

a. object, class b. class, object c. cookie, cake d. object, method

Computer Science & Information Technology

In a switch statement, when a break statement is encountered, an immediate transfer of control is made to

a. the default case of the switch statement b. a goto statement c. the else clause d. the statement beyond the end of the switch statement. e. none of these

Computer Science & Information Technology

On a single computer, Windows 10 can have multiple user accounts

Indicate whether the statement is true or false

Computer Science & Information Technology

Excel fills a column that is too narrow to display its contents with ________ signs

A) pound (#) B) dollar ($) C) plus (+) D) caret (^)

Computer Science & Information Technology