Stack accessible by all member functions of a class
-
29-10-2019 - |
Question
I want all member functions of a class to have access to the same stack. Each member function will push data to the stack and pop data from the stack.
I am having a hard time declaring the stack. I have a cpp file and a header file it won't let me declare a stack in the header file. Does anyone have an example of how this could be done?
I need to use a stack as a LIFO data structure makes more sense as I only need to access the last item placed on the stack.
I tried declaring it in the header file as a protected member with stack<int> items;
but get a compile error "stack does not name a type".
Adam
Solution
Don't pass around basic data structures.
Your stack represents something, maybe a stack of Orders
in a sandwich shop, or a stack of Pancakes
being rendered in glorious 5D. Create an object of type Pancakes
, or Orders
as appropriate, and pass a reference to objects that need to know about it.
// pancakes.h
#include <stack>
class Pancake;
class Pancakes
{
public:
void addPancake(const Pancake& pancake);
Pancake& top() const;
void pop();
private:
std::stack<Pancake> m_pancakes;
};
// pancakes.cpp
#include "pancakes.h"
#include "pancake.h"
void Pancakes::addPancake(const Pancake& pancake)
{
m_pancakes.push(pancake);
}
Pancake& Pancakes::top() const
{
return m_pancakes.top();
}
void Pancakes::pop()
{
m_pancakes.pop();
}
OTHER TIPS
Ok, let's assume you're using a std::stack.
class MyClass
{
private:
std::stack<int>& myStack_;
public:
MyClass(std::stack<int>& stack) : myStack_(stack) { };
}; // eo MyClass
Just pass a reference to the stack each time you make an instance of MyClass
. This also avoids singletons:
std::stack<int> globalStack;
MyClass class1(globalStack);
MyClass class2(globalStack);
Be sure you do a
#include <stack>
and additionally either do a
using namespace std;
or a
std::stack<int> items;
in the header file.