It's been a while since I've used C++, but I'll have a go at answering this:
Quote:
|
Originally Posted by DogDays
1. Why deliberately miscast pBase to the wrong type? Sounds like a coding error to me.
|
Presumably, the author is inferring from the names of the classes that DerivedClass inherits from BaseClass. Casting a class as one of its ancestors is legitimate.
Quote:
|
Originally Posted by DogDays
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.
|
The author is using casting in this case to prove a point, rather than to be of any practical use. If a method is virtual, then an object will always use the "right" method, no matter what it is cast as. If a method is not virtual, then the method used will depend on what the object has been cast as.
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.