(Member Object Destructors) Write a program illustrating that member object destructors are called for only those member objects that were constructed before an exception occurred.

What will be an ideal response?

```
// Class Item definition.

class Item
{
public:
Item( int ); // constructor takes int parameter
~Item(); // destructor
private:
int value;
}; // end class Item
```
```
// Class Item member function definition.
#include
#include
#include "Item.h"
using namespace std;

// constructor takes int parameter
Item::Item( int val ) : value( val )
{
cout << "Item " << value << " constructor called\n";

// if value is 3, throw an exception for demonstration purposes
if ( value == 3 )
throw runtime_error( "An exception was thrown" );
} // end Items constructor

// destructor
Item::~Item()
{
cout << "Item " << value << " destructor called\n";
} // end Items destructor
```
```
// Class ItemGroup definition.
#include "Item.h"

class ItemGroup
{
public:
ItemGroup(); // constructor
~ItemGroup(); // destructor
private:
Item item1;
Item item2;
Item item3;
Item item4;
Item item5;
}; // end class ItemGroup
```
```
// Class ItemGroup member function definition.
#include
#include "ItemGroup.h"
using namespace std;

// constructor
ItemGroup::ItemGroup()
: item1( 1 ), item2( 2 ), item3( 3 ), item4( 4 ), item5( 5 )
{
cout << "ItemGroup constructor called\n";
} // end ItemGroup constructor

// destructor
ItemGroup::~ItemGroup()
{
cout << "ItemGroup destructor called\n";
} // end ItemGroup destructor
```
```
#include
#include
using namespace std;

#include "ItemGroup.h"

int main()
{
cout << "Constructing an object of class ItemGroup\n";

try // create ItemGroup object
{
ItemGroup itemGroup;
} // end try
catch( runtime_error &exception )
{
cout << exception.what() << '\n';
} // end catch

return 0;
} // end main
```
Constructing an object of class ItemGroup
Item 1 constructor called
Item 2 constructor called
Item 3 constructor called
Item 2 destructor called
Item 1 destructor called
An exception was thrown

Computer Science & Information Technology

You might also like to view...

Bullets effectively present an overview or summary of information, but you should limit their use to a maximum of _____ per slide.

A. three to five B. five to seven C. eight to ten D. six to nine

Computer Science & Information Technology

Visit the Bureau of Labor Statistics site at www.bls.gov and search for information about employment trends affecting systems analysts, computer programmers, and software engineers.

What will be an ideal response?

Computer Science & Information Technology