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

Disable ads (and more) with a membership for a one time $2.99 payment

Test your C++ skills with our quiz based on Bruce Eckel's 'Thinking in C++'. Dive into object-oriented programming, advanced topics, and fundamentals. Perfect for learners and experts alike. Assess your knowledge and become a C++ master!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


Why are destructors often made virtual in base classes?

  1. To prevent memory leaks

  2. To enforce class abstractness

  3. For performance reasons

  4. To ensure correct destructor chaining

The correct answer is: 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.