base *bptr;
derived *dptr;
dptr=new derived;
bptr=dptr;
delete bptr;
Does that actually delete the entire derived object? Does it toss an error? Does it half-delete the object, causing issues? Is that a generally undefined behavior?
Inheritance Deletion question
I'm reading through the inheritance/abstraction tutorials on cplusplus.com and something is not terribly clear.
Since base pointers can be assigned to derived objects, what happens when delete is used with the base pointer.
For example:
If you make the base object have a virtual destructor then it's perfectly fine. If you don't the results are undefined.
"If you make the base object have a virtual destructor then it's perfectly fine. If you don't the results are undefined."
Arnt all destructors virtual by default?
Arnt all destructors virtual by default?
Well, I suppose that creates another question... [which I can experiment to find the answer myself if it's not answered by the time I can...]
Once you virtualize the destructor, does the base destructor still get called when the derived object is destroyed, or does the redefinition replace it?
Once you virtualize the destructor, does the base destructor still get called when the derived object is destroyed, or does the redefinition replace it?
Its been a while since ive used inheritance like this (b/c its relitivly slow) but yeah the destructors should be called, trickeling down the virtual pointer list... starting from the base object and going down through each derivied object in order, up to the last objects destructor. or maybe its the other way around, sorry i kinda forget.
can someone else refresh me? thx
can someone else refresh me? thx
ah okay,
how did you trigger it, did you call:
delete bptr;
or
delete dptr;
off hand it seems to me that if you call delete with the base, it will trickel down, and if you call delete with the derived pointer the destructor calls will propogate up.
aggg i forget
how did you trigger it, did you call:
delete bptr;
or
delete dptr;
off hand it seems to me that if you call delete with the base, it will trickel down, and if you call delete with the derived pointer the destructor calls will propogate up.
aggg i forget
Destuctors in C++ are not virtual by default. You must make a destructor virtual if you want the destructors in derived classes to be called when a base class is destroyed.
It is generally a good idea to always make a destructor virtual to avoid problems in the future. The exception would be the case where an additional 4 bytes added to the size of the class is a problem.
It is generally a good idea to always make a destructor virtual to avoid problems in the future. The exception would be the case where an additional 4 bytes added to the size of the class is a problem.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement