-
virtual destructors
In which of the following scenarios should a destructor be declared virtual in a base class?
A. When the destructor of the base class will be doing the clean-up of the derived class data
B. When an implementation for the derived class destructor is not desired
C. When a derived class allocates system resources which are released in its destructor
D. When the developer wants to ensure that a derived class destructor is invoked when an instance is destroyed through a base class pointer
E. When the default constructor of the base class is declared as virtual
Ok, I feel:
* A is correct, because destructor are not inherited. And IIRC to call the base class destructor from the derived class, the base class must be virtual.
* B is incorrect, because we only use virtual if we want the derived class to over right the base class destructor.
* C is correct, because we want the derived class destructor to more the derived classes memory.
* D is incorrect, because the derived class destructor is not invoked when the base class is destroyed.
* E is incorrect, as the constructor is separate from the destructor.
Can someone please confirm. Thx.
-
The answer is D, and to understand why read this FAQ answer: When should my destructor be virtual?
-
The idea behind virtual is the polymorphic concept.
If you create a new instance of a derived class and put it inside a pointer to its base class and call functions through that pointer, the compiler will call the base class's functions, even though a derived function may already exist. This is because the compiler doesn't know the pointer is actually pointing to a derived class instance.
Now, if you would make that function virtual, the compiler will "look up" the correct type and call the appropriate function, in this case, the derived function if it exists, or the base class's, if it does not.
The same applies to the destructor.
The destructor by the compiler when an object is destroyed.
So with that knowledge in mind, the answers to these questions are:
A) Incorrect, because the derived constructor will always be called when a derived object is destroyed.
B) Incorrect, because it makes no sense. Virtual does not "steal" a function call.
C) Incorrect, because of the same reason as A).
D) Correct, because if delete is called on a pointer to the base class, ONLY the base class's constructor will be called (since the compiler thinks it's a Base class object the pointer is pointing to). Making it virtual fixes this because of the discussion above.
E) Incorrect, as you say.