M
Marcelo De Brito
Hi!
I am a little bit confused on virtual destructos and upcasting through
pointers. The following code explains my doubt:
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
b2* b2p = new d2; //Upcast
}
The output I got is:
b1::~b1()
d2::~d2()
b2::~b2()
Why did only the "b2" pointer "b2p" called the derived class "d2"
destructor?
I know the virtual statement has to do with it, but since an upcasting
is being made, I thought the base class pointer "b2p" would have
access only to the base class members and, thus, would be not able of
calling any member declared in the derived class ("d2"), including the
destructor "d2::~d2()".
I appreciate any comment, suggestion, and etc.
Thank You!
Marcelo
I am a little bit confused on virtual destructos and upcasting through
pointers. The following code explains my doubt:
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
b2* b2p = new d2; //Upcast
}
The output I got is:
b1::~b1()
d2::~d2()
b2::~b2()
Why did only the "b2" pointer "b2p" called the derived class "d2"
destructor?
I know the virtual statement has to do with it, but since an upcasting
is being made, I thought the base class pointer "b2p" would have
access only to the base class members and, thus, would be not able of
calling any member declared in the derived class ("d2"), including the
destructor "d2::~d2()".
I appreciate any comment, suggestion, and etc.
Thank You!
Marcelo