View Single Post
Old Feb 27th, 2006, 9:59 AM   #1
DogDays
Newbie
 
DogDays's Avatar
 
Join Date: Feb 2006
Location: Chicago
Posts: 1
Rep Power: 0 DogDays is on a distinguished road
Virtual Destructors

Every example I've found that demonstrates why the base class destructor needs to be virtual has the following basic code snippet.

DerivedClass* pDerived = new DerivedClass();
BaseClass* pBase = (BaseClass*)pDerived;
delete pBase;

Which for me raises the following questions.

1. Why deliberately miscast pBase to the wrong type? Sounds like a coding error to me.

2. If the consumer needs access to some functionality in the base class not explicitly provided by the derived class, then modify the OO design to provide it rather than "hack" your way into the base class.

I prototyped this with Visual C++ 6.0 and as long as you delete the same object you created, i.e. the derived class, the derived class destructor is always invoked without use of virtual.

I've been job searching and this seems to be a favorite quiz question.
Which brings up the concept of technical tests for interviews, but that's another story.
DogDays is offline   Reply With Quote