Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of pure virtual functions during derived class destruction - In C++

During destruction of the derived class object, i first hit the derived class destructor and then the base class destructor (which is as expected). But i was curious to find out - at what point does the functions of the derived class go out of scope (are destroyed).

Does it happen as soon as the control leaves the derived class destructor and goes toward the base? Or does it happen once we done with the base class destructor also.

Thanks

like image 930
Manav Sharma Avatar asked Dec 16 '22 23:12

Manav Sharma


2 Answers

Once the destructor of the most derived class finishes, the dynamic type of the object can be considered that of the next less-derived-type. That is, a call to a virtual method in the base destructor will find that the final overrider at that point in time is at base level. (The opposite occurs during construction)

struct base {
   base() { std::cout << type() << std::endl; }
   virtual ~base() { std::cout << type() << std::endl; }
   virtual std::string type() const {
      return "base";
   }
};
struct derived : base {
   virtual std::string type() const {
      return "derived";
   }
};
int main() {
   base *p = new derived;
   std::cout << p->type() << std::endl;
   delete p;
}
// output:
// base
// derived
// base
like image 121
David Rodríguez - dribeas Avatar answered Dec 19 '22 13:12

David Rodríguez - dribeas


Functions don't get destroyed.

Virtual functions however get their entry in the v-table erased as soon as the derived destructor finishes so you can't call derived virtual functions from the base d'tor.

like image 24
shoosh Avatar answered Dec 19 '22 14:12

shoosh