Before you mark this question as a duplicate, please realize that I did have a look at this post and other similar ones on the site. My issue is not with understanding how variable scopes and/or the preprocessor work. I've got those down.
I can't figure out this pesky problem in my code. I'm just trying to model a stack data structure using C++. The compiler keeps complaining that size
and capacity
were not declared in this scope (for Stack.cpp
). There are three files:
- Stack.h
- Stack.cpp
- Main.cpp
Below are the code snippets for the header file and the .cpp file:
Stack.h
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class Stack
{
public:
Stack();
void push(T item);
T pop();
private:
int size;
const int capacity = 10;
T items[];
};
#endif
Stack.cpp
#include "Stack.h"
using namespace std;
template<typename T>
Stack::Stack() : items[capacity]
{
size = 0;
}
template<typename T>
void Stack::push(T item)
{
if(size == capacity)
{
cout << "No more room left. Unable to add items.";
}
else
{
items[size-1] = item;
size++;
}
}
template<typename T>
T Stack::pop()
{
if(size == 0)
{
cout << "Stack is empty. There is nothing to remove.";
}
else
{
size--;
}
}
The compiler also strangely complains that "'template class Stack' used without template parameters void Stack::push(T item)", which doesn't make much sense, seeing as how I did use the template header before the member function.
Could someone please clarify what I did wrong?