I have an example with the custom Stack implementation. As far as I understood, the .h
files should only contain declarations and the cpp
files should only contain implementations. I have found an example of a custom Stack on the cplusplus.com/stack_example and it looks something like the following.
Stack.h file
#ifndef _STACK_H_
#define _STACK_H_
#include <iostream>
#include "Exception.h"
template <class T>
class Stack {
public:
Stack():top(0) {
std::cout << "In Stack constructor" << std::endl;
}
~Stack() {
std::cout << "In Stack destructor" << std::endl;
while ( !isEmpty() ) {
pop();
}
isEmpty();
}
void push (const T& object);
T pop();
const T& topElement();
bool isEmpty();
private:
struct StackNode { // linked list node
T data; // data at this node
StackNode *next; // next node in list
// StackNode constructor initializes both fields
StackNode(const T& newData, StackNode *nextNode)
: data(newData), next(nextNode) {}
};
// My Stack should not allow copy of entire stack
Stack(const Stack& lhs) {}
// My Stack should not allow assignment of one stack to another
Stack& operator=(const Stack& rhs) {}
StackNode *top; // top of stack
};
Now I have question. This .h
file obviously reveals some implementation details. The constructor and the destructor are both implemented in the .h
file. In my understanding, those should be implemented in .cpp
file. Also, there is that struct StackNode
which is also implemented in the .h
file. Is that even possible to implement in the .cpp
file and only declare it in the header file? As a general rule, wouldn't it be better if those were in the .cpp
implementation file? What would be the best way to code this thing so that it follows C++ rules?