I am very new to C++ and i have been given an assignment to display stack implementation using array in C++. I developed the Program using two .cpp files i.e main and calculation part. But after i submitted by assignment the teacher told me tu use the header file to develop the program . I am trying to get the same output using the header file but it gives undefined reference error. Any help would be much appreciated.
My Calc.h file
#include <iostream>
using namespace std;
#define SIZE 100
class Calc {
int *arr,n,top=-1;
public:
Calc(int size = SIZE); // constructor
~Calc();
public:
void push(int val);
void pop();
void displayStackElems();
};
Calc::Calc(int size)
{
arr = new int[size];
n = size;
top = -1;
}
// Destructor to free memory allocated to the stack
Calc::~Calc() {
delete[] arr;
}
Calc.cpp
#include <iostream>
#include "Calc.h"
using namespace std;
void Calc::push(int val) {
if (top >= n-1)
cout<<"Stack Overflow"<<endl;
else{
top++;
arr[top]=val;
}
}
void Calc::pop() {
if (top <=-1)
cout<<"Stack Underflow"<<endl;
else{
cout << "The popped element is " << arr[top] << endl;
top--;
}
}
void Calc::displayStackElems() {
if(top >=0){
cout<<"Stack elements are : ";
for (int i = top; i >=0 ; i--)
cout << arr[i] << " ";
cout<<endl;
} else
cout<<"Stack is empty";
}
Main.cpp
#include <iostream>
using namespace std;
#include "Calc.h"
int main() {
int LengthOfStack;
cout<<"Enter the length of the stack you want : \n"<<endl;
cin >> LengthOfStack;
Calc c(LengthOfStack);
int choice,value;
cout<<"1. Push in arr"<<endl;
cout<<"2. Pop from arr"<<endl;
cout<<"3. Display arr"<<endl;
cout<<"4. Exit"<<endl;
do {
cout<<"Enter choice : "<<endl;
cin >> choice;
switch(choice) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin >> value;
c.push(value);
break;
}
case 2: {
c.pop();
break;
}
case 3: {
c.displayStackElems();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
} while (choice != 4);
return 0;
The Error Log :
6_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: CMakeFiles/untitled.dir/main.cpp.o:/cygdrive/z/Academics/Tezu/DS/untitled/main.cpp:25: undefined reference to `Calc::push(int)'
/usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: CMakeFiles/untitled.dir/main.cpp.o: in function `main':
/cygdrive/z/Academics/Tezu/DS/untitled/main.cpp:29: undefined reference to `Calc::pop()'
/usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: /cygdrive/z/Academics/Tezu/DS/untitled/main.cpp:33: undefined reference to `Calc::displayStackElems()'
collect2: error: ld returned 1 exit status