On 20.08.2015 23:08, JiiPee wrote:
> I think its Sutter who writes:
>
http://www.gotw.ca/publications/mill18.htm
> // Example 3: Obvious need for virtual destructor.
> class Base { };
>
> class Derived : public Base {};
>
> Base* b = new Derived;
> delete b; // Base::~Base() had better be virtual!
>
[snip]
>
> class Derived : public Base {};
>
> Base* b = new Derived;
> delete (Derived*)b;
>
> Its not virtual but seems to work the same as the virtual version.
> So, just wondering why he said "it better be virtual" as I can show here
> that there is a way to get it working without virtuality.
In most code the deleting action is automated.
The cast you use is automated by std::shared_ptr (provided the complete
type is known at the point of construction), but e.g. std::unique_ptr
does not remember the original when the smart pointer is upcasted.
> Or is there a
> mistake in my version? I tested it... it seems to delete all objects
> from all classes.
It's technically OK, just as using goto is technically OK.
It's just very fragile, very error-prone.
> Yeah, I understand delete (Derived*)b; is not a good way to do stuff....
> but is that the only issue here?
No.
For example, the destructor might be the only method available to make
Base polymorphic (at least one virtual function), which it needs to be
for typeid and dynamic_cast (called RTTI, Run-Time Type Information).
Cheers & hth.,
- Alf