(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...

Use the headers attribute on the ___ tag to correspond to the id attribute on a tag.

a. ``` ``` b. ``` ``` d. ```

```

Computer Science & Information Technology

In a transaction processing cycle, ______ involves updating one or more databases in an organization with new transactions.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology

Although commonly referred to as a state, the Up frame is never actually visible in the movie.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

To insert a header, choose Header from the ____________________ tab, in the ____________________ group.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology