Reputation: 2975
I have written a function for Stack where the function top() shows the top of the stack:
class RuntimeException{
private:
string errorMsg;
public:
RuntimeException(const string& err){errorMsg = err;}
string getMessage() const {return errorMsg;}
};
class StackEmpty : public RuntimeException{
public:
StackEmpty(const string& err) : RuntimeException(err){}
};
template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
try{
if(empty()) throw StackEmpty("Top of Empty Stack");
return S[t];
}
catch(StackEmpty& se){
cout << se.getMessage()<<"\n";
}
}
int main()
{
ArrayStack <int> A;
cout << "######\n";
cout << A.top() << "\n";
cout << "######\n";
}
It shows below compilation warning:
$ g++ -Wall Stack.cpp -o Stack
Stack.cpp: In member function `const E& ArrayStack<E>::top() const [with E = int]':
Stack.cpp:91: instantiated from here
Stack.cpp:61: warning: control reaches end of non-void function
The Output is:
$ ./Stack
######
Top of Empty Stack
6649957
######
Can someone tell what the warning is about and how to resolve it ? Also what does the the number '6649957' in output signifies?
Thanks
Upvotes: 1
Views: 4332
Reputation: 43311
In the case StackEmpty
is thrown, function doesn't return anything, though it is supposed to return const E&
.
template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
try{
if(empty()) throw StackEmpty("Top of Empty Stack");
return S[t];
}
catch(StackEmpty& se)
{
cout << se.getMessage()<<"\n";
// Return operator is missing ! Possibly you want this:
throw;
}
}
Edit. This is the way to use exception thrown from the method. You need to catch an exception in the client code, and not in the method itself.
template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
if(empty()) throw StackEmpty("Top of Empty Stack");
return S[t];
}
int main()
{
ArrayStack <int> A;
try
{
cout << "######\n";
cout << A.top() << "\n";
cout << "######\n";
}
catch(StackEmpty& se)
{
cout << se.getMessage()<<"\n";
}
}
Upvotes: 1