Re: Virtual Destructors And Upcasting
* Marcelo De Brito:
Hi!
Thank you very much for your reply.
I forgot to put two lines of code that would give the aforementioned
output. Then, the code must be:
#include <iostream>
using namespace std;
class b1 {
public:
~b1() {cout << "b1::~b1()" << endl;}
};
class d1 : public b1 {
public:
~d1() {cout << "d1::~d1()" << endl;}
};
class b2 {
public:
virtual ~b2() {cout << "b2::~b2()" << endl;}
};
class d2 : public b2 {
public:
~d2() {cout << "d2::~d2()" << endl;}
};
int main()
{
b1* b1p = new d1; //Upcast
delete b1p;
b2* b2p = new d2; //Upcast
delete b2p;
}
Now, the output is what I said in the previous message:
b1::~b1()
d2::~d2()
b2::~b2()
I should reformulate the question above: Why, when deleting the "b1p"
pointer, only the base class destructor is called
Formally it's Undefined Behavior to do 'delete p' when the dynamic type of the
object pointed to is different from the static referent type of p.
So formally anything could happen.
What happens in practice here is that the compiler simply assumes that the code
doesn't have UB, and since in C++ it's impractical to add any runtime check it
doesn't do that either, and so the result is the same as if you just had the
base type subobject.
and when deleting
the "b2p" pointer both base class and derived class destructors are
called?
Read up on "virtual" in your textbook.
I have read it so many times and I could not get the right message
from the text. But I appreciate and thank your explanation.
Uh, what book is that?
Short explanation: when a method m is virtual in a class B it's virtual in all
derived classes, and then when o is of statically known type B or a derived
class, a call o.m() effectively calls the first m implementation found by a
search starting in o's bottom-level *dynamic type* (d2 above) and up the
inheritance chains.
In practice, in C++ there's no actual search, but instead the same effect as the
search would yield is achieved in constant time by having a hidden pointer to a
type specific table of methods, in each object.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!