GeekInterview.com
Series: Subject: Topic:
Question: 60 of 267

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.
Asked by: joeychen | Member Since Mar-2010 | Asked on: Mar 27th, 2010

View all questions by joeychen

Showing Answers 1 - 2 of 2 Answers
phalder

Answered On : Apr 27th, 2010

View all answers by phalder

Possibly B is the best explanation

Yes  1 User has rated as useful.
  
Login to rate this answer.
Thunder2010

Answered On : Jun 15th, 2010

View all answers by Thunder2010

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).

  
Login to rate this answer.

Give your answer:

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

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.