![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Feb 2006
Location: Chicago
Posts: 1
Rep Power: 0
![]() |
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. |
|
|
|
|
|
#2 | ||
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
It's been a while since I've used C++, but I'll have a go at answering this:
Quote:
Quote:
If a destructor were not virtual, then it would change depending on what it was cast at. In the example you give, if the destructor were not virtual, C++ would call the destructor of BaseClass, rather than DerivedClass. This is a problem, because it could potentially lead to an object not being cleanly removed. For instance, if DerivedClass accessed a file, and BaseClass did not, then a non-virtual destructor could leave open filehandles lying around. Because there is often little reason to not have virtual constructors, it's highly recommended for safety's sake. And if you don't have a virtual constructor, you essentially bar your class from being used in functions that take an ancestor class argument if there is a chance your object will be destroyed. |
||
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|