The following example defines a constructor and destructor that print messages, so you can see exactly when these functions are called.
#include <iostream.h>
#include <string.h>
class Demo
{
public:
Demo( const char *nm );
~Demo();
private:
char name[20];
};
Demo::Demo( const char *nm )
{
strncpy( name, nm, 20 );
cout << "Constructor called for " << name << '\n';
}
Demo::~Demo()
{
cout << "Destructor called for " << name << '\n';
}
void func()
{
Demo localFuncObject( "localFuncObject" );
static Demo staticObject( "staticObject" );
cout << "Inside func\n";
}
Demo globalObject( "globalObject" );
void main()
{
Demo localMainObject( "localMainObject" );
cout << "In main, before calling func\n";
func();
cout << "In main, after calling func\n";
}
The program prints the following:
Constructor called for globalObject
Constructor called for localMainObject
In main, before calling func
Constructor called for localFuncObject
Constructor called for staticObject
Inside func
Destructor called for localFuncObject
In main, after calling func
Destructor called for localMainObject
Destructor called for staticObject
Destructor called for globalObject
For local objects, the constructor is called when the object is declared, and the destructor is called when the program exits the block in which the object is declared.
For global objects, the constructor is called when the program begins and the destructor is called when the program ends. For static objects, the constructor is called before the first entry to the function in which they're declared and the destructor is called when the program ends.