J
junw2000
Below is a simple code:
#include <iostream>
class base{
public:
base(): i(11){std::cout<<"base constructor"<<'\n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"base destructor"<<'\n';}
int i;
};
class derv1 : public base{
public:
derv1(){std::cout<<"derv1 constructor"<<'\n';}
void f(){}
~derv1(){std::cout<<"derv1 destructor"<<'\n';}
};
class derv2 : public derv1{
public:
derv2(){i=22;std::cout<<"derv2 constructor"<<'\n';}
~derv2(){std::cout<<"derv2 destructor"<<'\n';}
};
int main(){
base *b1;
derv1 *d1;
derv2 *d2 = new derv2;
b1 = d2;
std::cout<<b1<<" "<<d2->i<<'\n';
delete b1; //LINE1
std::cout<<"after delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?
Thanks.
Jack
#include <iostream>
class base{
public:
base(): i(11){std::cout<<"base constructor"<<'\n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"base destructor"<<'\n';}
int i;
};
class derv1 : public base{
public:
derv1(){std::cout<<"derv1 constructor"<<'\n';}
void f(){}
~derv1(){std::cout<<"derv1 destructor"<<'\n';}
};
class derv2 : public derv1{
public:
derv2(){i=22;std::cout<<"derv2 constructor"<<'\n';}
~derv2(){std::cout<<"derv2 destructor"<<'\n';}
};
int main(){
base *b1;
derv1 *d1;
derv2 *d2 = new derv2;
b1 = d2;
std::cout<<b1<<" "<<d2->i<<'\n';
delete b1; //LINE1
std::cout<<"after delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?
Thanks.
Jack