Mastering C++: A Comprehensive Quiz Based on 'Thinking in C++'

Question: 1 / 50

Why are destructors often made virtual in base classes?

To prevent memory leaks

To enforce class abstractness

For performance reasons

To ensure correct destructor chaining

When working with inheritance in object-oriented programming, it is common to have a class that serves as a base or parent class to other subclasses. These subclasses may also have their own destructor. By making the destructor virtual in the base class, it ensures that the destructors of all subclasses will be called in order to properly deallocate memory and prevent memory leaks. This is known as destructor chaining, which is essential for the proper execution of the program. Option A is incorrect because preventing memory leaks is not the main purpose of making destructors virtual in base classes. Option B is incorrect because enforcing class abstractness is unrelated to the use of virtual destructors. Option C is incorrect because virtual destructors may have a slight performance overhead, but it is not their main purpose. Therefore, the most suitable explanation for why destructors are often made virtual in base classes is to ensure correct destructor chaining in inheritance.