(Local Variable Destructors) Write a program illustrating that all destructors for objects constructed in a block are called before an exception is thrown from that block.
What will be an ideal response?
```
// Class TestObject definition.
class TestObject
{
public:
TestObject( int ); // constructor takes int parameter
~TestObject(); // destructor
private:
int value;
}; // end class TestObject
```
```
// Class TestObject member function definition.
#include
#include "TestObject.h"
using namespace std;
// constructor takes int parameter
TestObject::TestObject( int val ) : value( val )
{
cout << "TestObject " << value << " constructor\n";
} // end TestObject constructor
// destructor
TestObject::~TestObject()
{
cout << "TestObject " << value << " destructor\n";
} // end TestObject destructor
```
```
#include
#include
using namespace std;
#include "TestObject.h"
int main()
{
try // create objects and throw exception
{
// create three TestObjects
TestObject a( 1 );
TestObject b( 2 );
TestObject c( 3 );
cout << '\n';
// throw an exception to show that all three Objects created above
// will have their destructors called before the block expires
throw runtime_error( "This is a test exception" );
} // end try
// catch the Error
catch ( runtime_error &exception )
{
cerr << exception.what() << "\n";
} // end catch
return 0;
} // end main
```
TestObject 1 constructor
TestObject 2 constructor
TestObject 3 constructor
TestObject 3 destructor
TestObject 2 destructor
TestObject 1 destructor
This is a test exception
You might also like to view...
The ability to save your Office 2010 files with older file formats is known as ________ mode
Fill in the blank(s) with correct word
Structure objects are normally passed ____________ to a method.
a. by reference b. globally c. by value d. locally