#include <iostream>
using namespace std;
#define MAX 3
class hello_world
{
char *const buf;
int stack_ptr, destructor_calls;
bool init;
public:
// The recursive constructor
hello_world(char *const &str, int i = 0)
: buf(str), stack_ptr(0), init(false), destructor_calls(0)
{
if (i == MAX)
{
buf[i] = '\0';
cout << buf << endl;
return;
}
buf[i] = '0';
hello_world::hello_world(str, i + 1);
buf[i] = '1';
hello_world::hello_world(str, i + 1);
}
// The recusive destructor
~hello_world()
{
++destructor_calls;
if (!init) { cerr << "A destructor call within initialization has been terminated" << endl; return; }
int i = stack_ptr;
if (i == MAX)
{
buf[i] = '\0';
cout << buf << endl;
}
else
{
buf[i] = '0';
++stack_ptr; // since a destructor cannot take parameters
hello_world::~hello_world();
--stack_ptr;
buf[i] = '1';
++stack_ptr;
hello_world::~hello_world();
--stack_ptr;
// Printing total number of calls at final call
if (i == 0)
cout << endl << "\"destrucotr_calls\" = " <<
destructor_calls << endl;
}
}
void unlock()
{
init = true;
}
}; // end of class hello_world
int main()
{
char buf[MAX + 1];
cout << "Calling hello_world class constructor..." << endl;
hello_world h(buf);
h.unlock();
cout << "Calling hello_world class destructor..." << endl;
return 0;
}
/*
Output:
Calling hello_world class constructor...
000
A destructor call within initialization has been terminated
001
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
010
A destructor call within initialization has been terminated
011
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
100
A destructor call within initialization has been terminated
101
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
110
A destructor call within initialization has been terminated
111
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
A destructor call within initialization has been terminated
Calling hello_world class destructor...
000
001
010
011
100
101
110
111
"destrucotr_calls" = 15
Press any key to continue . . .
*/