Using a constructor and destructor. : Destructor « Class « C++






Using a constructor and destructor.

Using a constructor and destructor.
 

#include <iostream>
using namespace std;

#define SIZE 10

class stack {
  int stck[SIZE];
  int topOfStack;
public:
  stack();  // constructor
  ~stack(); // destructor
  void push(int i);
  int pop();
};

// constructor
stack::stack(){
  topOfStack = 0;
  cout << "Stack Initialized\n";
}

// destructor
stack::~stack(){
  cout << "Stack Destroyed\n";
}

void stack::push(int i){
  if( topOfStack == SIZE ) {
    cout << "Stack is full.\n";
    return;
  }
  stck[ topOfStack ] = i;
  topOfStack++;
}

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

int main()
{
  stack a, b;
  
  a.push(1);
  b.push(2);

  a.push(3);
  b.push(4);

  cout << a.pop() << " ";
  cout << a.pop() << " ";
  cout << b.pop() << " ";
  cout << b.pop() << endl;

  return 0;
}



           
         
  








Related examples in the same category

1.Constructing and Destructing sequence for two base classesConstructing and Destructing sequence for two base classes
2.Derived class call its base constructorDerived class call its base constructor
3.Derived constructor uses no parametersDerived constructor uses no parameters
4.Define and use the destructorDefine and use the destructor
5.System will call the destructorSystem will call the destructor
6.Implement a destructorImplement a destructor
7.Define destrcuctor outside the class definition