FAQ 30.03 What happens when an object is destroyed that doesn t have an explicit destructor?

FAQ 30.03 What happens when an object is destroyed that doesn't have an explicit destructor?

The compiler synthesizes a destructor for the object's class.

For example, if an object of class Fred is destroyed and class Fred doesn't provide an explicit destructor, the compiler synthesizes a destructor that destroys all the Fred object's member objects and base class subobjects. This is called memberwise destruction. Thus, if class Fred doesn't have an explicit destructor and an object of class Fred contains an object of class Member that has an explicit destructor, then the compiler's synthesized Fred::~Fred() invokes Member's destructor.

The built-in types (int, float, void*, and so on) can be regarded as having destructors that do nothing.

 #include <iostream> using namespace std; class Member { public:   ~Member() throw(); }; Member::~Member() throw() { cout << "destructing a Member object\n"; } class Fred { public:                                                      <-- 1 protected:   Member member_; }; int main() {   {     Fred x;     cout << "before destructing a Fred\n";   }                                                  <-- 2   cout << "after destructing a Fred\n"; } 

(1) Fred doesn't have an explicit destructor

(2) Compiler-synthesized destructor Fred::~Fred() called here

The compiler's synthesized Fred::~Fred() calls Member::~Member() automatically, so the output is

 before destructing a Fred destructing a Member object after destructing a Fred 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net