Stack using Constructor and Destructor in C++ programming language: This Stack program is created based on C++ source code. In this code we are using “Constructor and destructor” accordingly. Here constructor is used to initialize the values and destructor is used to destroy the created memory space. Few stack operations also been performed in this C++ tutorial. They are,
- Stack PUSH operation,
- Stack POP operation.
- Read: Call by Reference programs with example code
Program Explanation:
There is a stack class namely STK. It has few data members and function declarations. The data members are T1 and stk1[SIZE]. The functions declarations are PUSH(int a) and POP(). After a class definition stack’s construction process is takes place. After a construction the stack will be destroyed by using a destructor. Stack object creations and parameter callings are also the part of this program. An example program is given below.
- Related: Constructor in C++
C++ Stack Program:
Question: Write a program for stack using constructor and destructor in C++ with example.
[SEE: C Program Tutorials] & [IT Companies Details]
#include<iostream.h> #include<conio.h> #define SIZE 100 // Stack class definition class STK { int T1, stk1[SIZE]; public: STK(); // STACK constructor ~STK(); // Stack destructor void PUSH(int a); int POP(); }; // Stack constructor method STK::STK() { T1=0; cout<<"Stack Begins.\n"; } // Stack Destructor method STK::~STK() { cout<<"Stack is destroying \n"; } void STK::PUSH(int a) { if(T1==SIZE) { cout<<"Stack is Full"; return; } stk1[T1]=a; T1++; } int STK::POP() { if(T1==0) { cout<<"This Stack is Underflow.\n"; return 0; } T1--; return stk1[T1]; } int main() { clrscr(); STK x, y; // It creates TWO stack objects x.PUSH(1); y.PUSH(2); x.PUSH(3); y.PUSH(4); cout<<x.POP()<<" "; cout<<x.POP()<<" "; cout<<y.POP()<<" "; cout<<y.POP()<<"\n"; getch(); return 0; }
- Learn [ Aptitude ] – [ Placement Papers ] – [ Spoken English ]