fpelliccioni

lifetime and virtuals

Nov 11th, 2013
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct base {
  4.     base()
  5.     {
  6.         std::cout << "base is under construction, derived unborn" << std::endl;
  7.         f();
  8.     }
  9.  
  10.     virtual ~base()
  11.     {
  12.         std::cout << "base dtor" << std::endl; 
  13.         f();
  14.     }
  15.  
  16.     virtual void f()
  17.     {
  18.         std::cout << "base::f()" << std::endl;
  19.     }
  20. };
  21.  
  22. struct derived : base {
  23.     derived()
  24.     {
  25.         std::cout << "derived is under construction" << std::endl;
  26.     }
  27.  
  28.     virtual ~derived()
  29.     {
  30.         std::cout << "derived no longer exists" << std::endl;  
  31.     }
  32.  
  33.     virtual void f() override
  34.     {
  35.         std::cout << "derived::f()" << std::endl;
  36.     }
  37. };
  38.  
  39. void f()
  40. {
  41.     base* b = new derived;
  42.     std::cout << "derived object X is alive" << std::endl; 
  43.     b->f();
  44.     delete b;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment