Knowee
Questions
Features
Study Tools

Why is it recommended to declare a virtual destructor in a base class? (2 Points) a) To prevent memory leaks b) To allow dynamic casting c) To ensure proper destruction of derived class objects d) To make the destructor public

Question

Why is it recommended to declare a virtual destructor in a base class? (2 Points)

a) To prevent memory leaks

b) To allow dynamic casting

c) To ensure proper destruction of derived class objects

d) To make the destructor public

🧐 Not the exact question you are looking for?Go ask a question

Solution

The main reason to declare a virtual destructor in a base class is to ensure proper destruction of derived class objects (option c).

Here's a step-by-step explanation:

  1. In C++, when a derived class object is deleted through a pointer to a base class that has a non-virtual destructor, results are undefined.

  2. This is because the base class's destructor does not know about the derived class and its members, so it cannot properly delete them. This can lead to memory leaks (option a), as the memory allocated for the derived class object is not freed.

  3. Declaring a virtual destructor in the base class ensures that the derived class's destructor is called when an object is deleted through a base pointer, which allows for proper cleanup of the derived class object.

  4. This has nothing to do with allowing dynamic casting (option b) or making the destructor public (option d). A destructor can be virtual regardless of its access specifier (public, protected, or private), and dynamic casting is related to runtime type identification, not object destruction.

This problem has been solved

Similar Questions

What is the purpose of a virtual base class in C++?

2. Which of the following gets called when an object is being created?A. ConstructorB. Virtual FunctionC. DestructorsD. Main

Destructor of a class is used ______Options: Pick one correct answer from belowTo modify the data whenever requiredTo destroy an object when the lifetime of an object endsTo initialize the data members of an object when it is createdTo call private functions from the outer world

Discuss the importance of virtual base class with the help of an example.

3. Can we have a virtual Destructor?A. YesB. No

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.