Saturday 7 July 2018

virutal distructor

 
class base {
  public:
    base()    
    { cout<<"Constructing base \n"; }
    ~base()
    { cout<<"Destructing base \n"; }    
};
 
class derived: public base {
  public:
    derived()    
    { cout<<"Constructing derived \n"; }
    ~derived()
    { cout<<"Destructing derived \n"; }
};
 
int main(void)
{
  derived *d = new derived(); 
  base *b = d;
  delete b;
  getchar();
  return 0;
}
Although the output of following program may be different on different compilers, when compiled using Dev-CPP, it prints following:
Constructing base
Constructing derived
// If virtual ~base()
//then call first : "Destructing Dervied" Destructing base

No comments:

Post a Comment