title: C++ Creating a copy constructor for stack class
body: <p>I have defined a stack class containing methods for pushing and popping values onto the stack. </p>
  
  <p>In the tester file (shown below), after running it, an occur occurs &amp; the program crashes. I know this is due to the function f, which creates an error as two pointers are pointing to the same location in memory. If i comment out the line f(s) when the function is called, the pop &amp; push functions work correctly and the output is correct. </p>
  
  <p>To fix this error, I have been asked to ; Create a copy constructor for this class to fix the above problem.</p>
  
  <p>I'm not really familiar with this, so any help would be appreciated in how to do this. Thanks</p>
  
  <p>Main Test file</p>
  
  <pre><code>#include "Stack.h"
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  using namespace std;
  
  void f(Stack &amp;a) {
      Stack b = a;
  }
  
  
  int main() {
  
      Stack s(2); //declare a stack object s which can store 2 ints
      s.push(4); //add int 4 into stack s
  
      //s = [4]
      s.push(13); //add int 13 into stack s
      //s = [4,13]
  
      f(s); //calls the function f which takes in parameter Stack a , and sets Stack b = to it.
      //error here - as 2 pointers point to the same location in memory !
      cout &lt;&lt; s.pop() &lt;&lt; endl; //print out top element(most recently pushed) element.
      //so should output 13
      return 0;
  }
  </code></pre>
  
  <p>Header File Code</p>
  
  <pre><code>#ifndef STACK_H
  #define STACK_H
  
  class Stack {
  public:
      //constructor
      Stack(int size);
  
      //destructor
      ~Stack();
  
      //public members (data &amp; functions)
      void push(int i);
      int pop();
  
  private:
      //private members (data &amp; functions)
      int stck_size;
      int* stck;
      int top;
  };
  
  #endif
  </code></pre>
  
  <p>Stack.cpp Code</p>
  
  <pre><code>#include "Stack.h"
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  using namespace std;
  
  Stack::Stack(int size){
      stck_size = size;
      stck = new int[stck_size];
      top = 0;
  }
  Stack::~Stack() {
      delete[] stck;
  }
  void Stack::push(int i) {
      if (top == stck_size) {
          cout &lt;&lt; "Stack overflow." &lt;&lt; endl;
          return;
      }
      stck[top++] = i;
  }
  
  int Stack::pop() {
      if (top == 0) {
          cout &lt;&lt; "Stack underflow." &lt;&lt; endl;
          return 0;
      }
      top--; //decrement top so it points to the last element istead of the empty space at the top.
      return stck[top];
  }
  </code></pre>