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...

Which of the following statements about regular expressions is true.

a. The set of braces containing two numbers, {n,m}, matches between n and m occurrences (inclusively) of the pattern that it quantifies. b. All of the regular expression quantifiers are greedy; they’ll match as many occurrences of the pattern as possible until the pattern fails to make a match. c. If a quantifier is followed by a question mark (?), the quantifier becomes lazy and will match as few occurrences as possible as long as there is a successful match. d. All of the above.

Computer Science & Information Technology

Which of the following would NOT be considered a design modification of a report?

A) Change the table on which the report is based. B) Change the placement of controls in a report. C) Add or remove controls. D) Change the format of controls.

Computer Science & Information Technology

How do you know that the Link to Previous feature in the Header & Footer Tools tab is active?

A) It is not grayed out like many of the other buttons on the Header & Footer Tools tab B) It displays with a dark gray background C) It displays with an orange color D) It shows with a dark black border

Computer Science & Information Technology

Most restored systems have some amount of lost data based on when the last backup took place.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology