Suppose we have the following files (taken from The C++ Programming language by B.Stroustup):
stack.h
namespace Stack{
void push(int);
int pop();
class Overflow{};
}
stack.cpp
#include "stack.h"
namespace Stack{
const int max_size = 1000;
int v[max_size];
int top;
class Overflow{};
}
void Stack::push(int elem){
if(top >= max_size){
throw Overflow();
}
v[top++] = elem;
}
int Stack::pop(){
if(top <= 0){
throw Overflow();
}
return v[--top];
}
I don't understand why declaration / definition (?) of class Overflow{} in stack.h has to be also written in stack.cpp?
Is it at all correct to write such code?
UPDATE
main.cpp
#include <iostream>
#include "stack.h"
using namespace std;
int main(){
try{
int a = 0;
while(true){
Stack::push(a++);
}
} catch(Stack::Overflow){
cout << "Stack::Overflow exception, YEAH!" << endl;
}
return 0;
}
I compile the code with: g++ main.cpp stack.cpp -o main
g++ i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
UPDATE (Solution)
Having tried g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3 the code gave me an error: stack.cpp:7:9: error: redefinition of ‘class Stack::Overflow’. Which is of course correct.
Summary: the previously stated version of g++ on mac has a bug.