Base Class Destructor

In C++, which of following statements accurately describe a base class destructor calling a virtual function override of a derived class?

A. the base class destructor calls the virtual function of the base class and not of the derived class.

B. the base class destructor calls the virtual function override of the derived class through th vtable.

C. the C++ compiler maintains the overridden virtual function pointers in a separate structure when it sees the call in a destructor. The call is then resolved through this structure.

D. the base class destructor cannot call the virtual function override of the derived class because the derived class portion of the data may be in an undefined state.

E. the language does not permit calling a virtual function override in either a constructor or the destructor of the base class.

Questions by joeychen

Showing Answers 1 - 6 of 6 Answers

Thunder2010

  • Jun 15th, 2010
 

Explanation:
In C++, if you call a virtual function from a constructor or destructor, the compiler calls the instance of the virtual function defined for the class being constructed (for example, Base::SomeVirtFn if called from Base::Base), not the most derived instance. As you say, this is because the vtable is not fully initialized until the most derived constructor executes. Another way to think of it is that the derived class is not created yet.


Similarly, when you call a virtual function from a destructor, C++ calls the base class function because the derived class has already been destroyed (its destructor has been called). While this behavior can lead to unexpected results (which is why it's considered bad programming practice to call a virtual function from a constructor or destructor).

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions