איתן לוי
איתן לוי

Reputation: 433

A question about syntax in inheritance of exceptions

I have the following class that represents a stack.

template <class T>
class stack {
    ...
public:
    explicit stack(int max_size = 100);
    stack(const Stack& s);
    ~stack();
    stack& operator=(const Stack&);
    void push(const T& t);
    void pop();
    T& top();
    const T& top() const;
    int getSize() const;
    class Exception : public std::exception {};
    class Full : public Exception {};
    class Empty : public Exception {};
};

Now, I have a second class that inherits from stack. It is similar but it has a special method called popConditionalthat pops elements out of the stack until a generic condition is met by the top element of the stack.

If there is no such element, I am supposed to throw an exception from a class named NotFoundthat inherits from the class Exception defined in Stack. My question is what is the proper syntax:

template <class T>
class ConditionalStack : public Stack<T> {
public:
    class NotFound : public Exception {
        const char* what() const override { return "not found"; }
    };
};

Or

template <class T>
class ConditionalStack : public Stack<T> {
public:
    class NotFound : public Stack<T>::Exception {
        const char* what() const override { return "not found"; }
    };
};

If the first one is not correct, why is that the case? Shouldn't the class Exception be inherited as well?

Upvotes: 0

Views: 49

Answers (1)

Jarod42
Jarod42

Reputation: 217135

As Exception is a dependent name, you should use second snippet.

Upvotes: 2

Related Questions