Tuesday, December 13, 2011

Constructor and destructor

If baby takes birth and dies away immediately, then the "baby" (who belonged to MAN class) has performed two functions: "being born" and "dieing". Similarly there are TWO mercy functions for ANY C++ object:
1. constructor: After allocation of memory, initializes it.
and
2. destructor: Before deallocation of memory, de-initializes it.

Constructor gets called automatically when an object is created. and
destructor gets called automatically when an object is about to die (go out of scope).

#include <iostream>

using namespace std;

class Man
{
   float height;
   float weight;

public:
   Man()
   {
     cout << "Man born" << endl;
   }

   ~Man()
   {
      cout << "Man died" << endl;
   }
};

int main()
{
  Man Hritik;
  return 0;
}

No comments:

Post a Comment