Basic Constructor Destructor Concepts in C++


//This program illustrates when constructors and destructors are executed:

#include <iostream.h>
#include <conio.h>

class myclass {
public:
int who;
myclass(int id);
~myclass();
} glob_ob1(1), glob_ob2(2);
myclass::myclass(int id)
{
      cout << "Initializing " << id << "\n";
      who = id;
}
myclass::~myclass()
{
      cout << "Destructing " << who << "\n";
}
int main()
{
      //clrscr();
      myclass local_ob1(3);
      cout << "This will not be first line displayed.\n";
      myclass local_ob2(4);
      getch();
      return 0;
}
/*It displays this output:
Initializing 1
Initializing 2
Initializing 3
This will not be first line displayed.
Initializing 4
Destructing 4
Destructing 3
Destructing 2
Destructing 1
One thing: Because of differences between compilers and execution environments, you
may or may not see the last two lines of output*/


Custom Search