Showing posts with label Destructor. Show all posts
Showing posts with label Destructor. Show all posts

Constructor & Destructor Tutorial in C++


// Using a constructor and destructor.
#include <iostream.h>
#include <conio.h>
#define SIZE 100
// This creates the class stack.
class stack
{
      int stck[SIZE];
      int tos;
      public:
      stack(); // constructor
      ~stack(); // destructor
      void push(int i);
      int pop();
};

// stack's constructor function
stack::stack()
{
      tos = 0;
      cout << "Stack Initialized\n";
}
// stack's destructor function
stack::~stack()
{
      cout << "Stack Destroyed\n";
}
void stack::push(int i)
{
      if(tos==SIZE) {
      cout << "Stack is full.\n";
      return;
}

      stck[tos] = i;
      tos++;
}

int stack::pop()
{
      if(tos==0)
      {
            cout << "Stack underflow.\n";
            return 0;
      }
      tos--;
      return stck[tos];
}

int main()
{
      clrscr();
      stack a, b; // create two stack objects
      a.push(1);
      b.push(2);
      a.push(3);
      b.push(4);
      cout << a.pop() << " ";
      cout << a.pop() << " ";
      cout << b.pop() << " ";
      cout << b.pop() << "\n";
      getch();
      return 0;
}

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