Manav Sharma
Manav Sharma

Reputation: 1093

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

Upvotes: 4

Views: 700

Answers (2)

shoosh
shoosh

Reputation: 79013

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.

Upvotes: 4

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

Upvotes: 8

Related Questions